objectbox-dart
objectbox-dart copied to clipboard
@Unique with replace strategy that update instead of deleting and inserting a new one
Right now, @Unique with conflict: ConflictStrategy.replace remove the old object and insert a new one, this behavior causes a null relation if there's data that has relation to the old object(the one before deleting), and after deleting and inserting a new object, the related item's relations aren't updated to the new object.
Agreed. This messes up relations big time and since neither non-integer primary keys nor composite indices are supported, relations are currently a nightmare to deal with. Unfortunately other packages like isar suffer pretty much the same issues :(
I'll try an ugly workaround in the meanwhile lol:
@Entity()
class TestModel {
@Id()
int objectId = 0;
@Unique(onConflict: ConflictStrategy.replace)
String id; // UUID
String name;
TestModel({
required this.id,
required this.name,
});
Future save() async {
final existing = objectBox.store
.box<TestModel>()
.query(TestModel_.id.equals(id))
.build()
.findFirst();
if (existing != null) {
print('update');
objectId = existing.objectId;
objectBox.store.box<TestModel>().put(this, mode: PutMode.update);
} else {
print('insert');
objectBox.store.box<TestModel>().put(this, mode: PutMode.insert);
}
}
}
//and you go like
var model = TestModel(id: Uuid().v4(), name: "Test 1");
model.save();
In case of saving multiple objects(putMany)? and what if there's a subobjects that I also want to handle?
Thanks for the request! Please thumbs up the first post, if you are interested in this.
Thanks! At this point when using ConflictStrategy.replace
with relations your code needs to take care of updating relations. Or maybe find a way to not having to use ConflictStrategy.replace
in the first place.
AFAIK this is not different from traditional relational databases?
Anyhow, I could have sworn we documented this, but it's not. So I'll add a note to the docs to be careful when using relations.
any updates on when this will be implemented