flutterdartaws-amplifyflutter-aws-amplifyaws-datastore

How to query Amplify datastore by custom type field value(Flutter)


I'm recently writing a flutter app which I need to manipulate the data in Amplify datastore. I'm able to query data by regular data type(e.g. String), but I'm not sure how to query by an array of custom type data.

Here is an example of my data model

type Shop @model {
    id: ID!
    owner: String
    item: [Item]
}

type Item{
    name: String
    color: String
}

How can I get a list of all Shop Models that have an Item named "abc", no matter what color it is.

I have done something like this, using the predicate "contains", but seems that it's not the right way to do so:

Future <List<Shop>> getShops(String itemName) async{
    try{
        final shops = await Amplify.Datastore.query(
            Shop.classType,
            where: Shop.ITEM.name.contains(itemName)
        );
        return shops;
    } catch (e){
        throw e;
    }
}

Solution

  • I found another way to achieve this. I changed the database structure to many-to-many relationship as below.

    type Shop @model{
      id: ID!
      items: [Item] @manyToMany(relationName: "ShopItem")
      owner: String
    }
    
    type Item @model{
      id: ID!
      shops: [Shop] @manyToMany(relationName: "ShopItem")
      name: String
      color: String
    }

    This will automatically generate a table called "ShopItem" which tells you if the Shop model and Item model are related.

    Then I just use the following code snippet to get a list of all Shop Models that have an Item named "abc":

    final dataList = await Amplify.DataStore.query(ShopItem.classType);
    
    List<Shop> shopList = [];
    
    for(var element in dataList){
      if(element.item.name == "abc"){
        shopList.add(element.shop);
      }
    }

    Might not be the best way, but I find it clearer and simpler than what I did before. Just let me know if there is a more efficient way.