How to Retrieve Data ompletely with Amplify?

26 views Asked by At

I'm trying to use Amplify with a "hasOne" relationship.

Here is my schema:

  type BudgetEntry @model @auth(rules: [{allow: public}]) {
  id: ID!
  title: String!
  description: BudgetDescription! @hasOne
  amount: Float!
}

type BudgetDescription @model @auth(rules: [{allow: public}]) {
    id: ID!
    description: String!
}

And here is how to retrieve the data:

  Future<void> _refreshBudgetEntries() async {
    try {
      final budgetEntries = await Amplify.DataStore.query(BudgetEntry.classType).then((entries) async {
        final descriptions = await Amplify.DataStore.query(BudgetDescription.classType);
        List<BudgetEntry> newEntries = [];
        for (var entry in entries) {
          newEntries.add(BudgetEntry(
            title: entry.title,
            description: descriptions.firstWhere((element) => entry.budgetEntryDescriptionId == element.id),
            amount: entry.amount,
            budgetEntryDescriptionId: entry.budgetEntryDescriptionId));
        }

        return newEntries;
      });
      safePrint('Entries: $budgetEntries');
      setState(() {
        _budgetEntries = budgetEntries;
      });
    } on DataStoreException catch (e) {
      safePrint('Something went wrong querying posts: ${e.message}');
    }
  }

Does a way exist to retrieve the data, ideally with only one query to the database? Or is there another more "elegant" way than the sample above?

I couldn't find information on this in the complete documentation: https://docs.amplify.aws/react/build-a-backend/more-features/datastore/relational-models/

0

There are 0 answers