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

Viewed 728

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.

1 Answers

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();
Related