flutterobjectbox

ObjectBox 1 to MANY: deleting the MANY of 1


I am struggling removing all related entries to a parent in a 1:n relationship. In the client order example this would be removing all orders of a customer. If I understand correctly, I cannot removeAll because this would remove also the orders of all other customers.

I also don't get this answer running. The _queryBuilder.backlink(... (see 2nd snippet) throws:

The argument type 'QueryRelationToOne<Order, Customer>' can't be assigned to the parameter type 'QueryRelationToOne<Order, Order>'.

@Entity()
class Customer {
  int id;
  @Backlink('customer')
  final orders = ToMany<Order>();
}
@Entity()
class Order {
  int id;
  final customer = ToOne<Customer>();
}
final QueryBuilder<Order> _queryBuilder = myBox.query();
_queryBuilder.backlink(Order_.customer, Order_.customer.equals(id));

Solution

  • If you want to remove the relations of the orders to the customer, it is possible to work with the ToMany backlink instead of updating the ToOne of each Order:

    Get the Customer, then clear the orders list, then applyToDb().

    If you want to remove the actual Order objects, access the ToMany, map to IDs and removeMany:

    final idsToRemove =
        customer.orders.map((order) => order.id).toList();
    orderBox.removeMany(idsToRemove);