Objectbox dart: how to filter based on a ToOne relation?

433

To query for orders by the item price for your model, you can use the following:

final ordersQuery = store.box<Order>().query()
  ..link(Order_.item, Item_.price < 100)
  ..build();

What this does, is:

  • first create a QueryBuilder<Order> with no conditions (no args to query())
  • then create a link to Item (which creates another query builder if we wanted to deep-link another entity, which we don't in this case)
  • then call build() on the "root" QueryBuilder, creating Query<Order>

The previous code is equivalent to:

final ordersQueryBuilder = store.box<Order>().query();
ordersQueryBuilder.link(Order_.item, Item_.price < 100);
final ordersQuery = ordersQueryBuilder.build();

Then, with either versions of the code, you can use the query as usual:

final orders = ordersQuery.find();

// As usual, don't forget to close the query to free up resources when you don't
// need it anymore. In case you missed it, queries are reusable so you can call 
// as many functions on ordersQuery as needed (it will work until you close()).
ordersQuery.close();
Share:
433
Salman Aljabri
Author by

Salman Aljabri

Updated on November 25, 2022

Comments

  • Salman Aljabri
    Salman Aljabri over 1 year

    lets say I have

    @Entity()
    class Order {
      int id;
      final item = ToOne<Item>();
      final customer = ToOne<Customer>();
    }
    
    @Entity()
    class Item {
      int id;
      int price;
      @Backlink()
      final orders = ToMany<Order>();
    }
    
    

    How to query filter the orders based on the items price. I know I can query the items and get the backlink orders but is it possible the other way around? eg:

    final orders = store.box<Order>().query(Order_.item.price < 100).build(). 
    

    The docs says filter data even across relations but I couldn't find a way to do it.

  • Salman Aljabri
    Salman Aljabri about 3 years
    Thanks . that worked. How would you do it for deep link? like filter further by item category?
  • Salman Aljabri
    Salman Aljabri about 3 years
    Just worked for me by doing: ordersQueryBuilder.link(Order_.item, Item_.price < 100).link(Item_.category, Category_.id.equals(id)); >> what a great library
  • vaind
    vaind about 3 years
    yep, that's exactly how you can deep link :)
  • vaind
    vaind about 3 years
    I also suggest looking at test code for other ways you can use the library (the docs for Dart are still a little scarce): github.com/objectbox/objectbox-dart/tree/main/objectbox/test
  • vaind
    vaind about 3 years
    Just to be clear, in your deep link example, you don't actually have to link, since you have the ID - this is the same: ordersQueryBuilder.link(Order_.item, Item_.category.equals(id).and(Item_.price < 100))