I have ToMany relation which looks like this,
@Entity()
class Pdf {
@Id()
int id;
Uint8List pdfData;
final String customerName;
@Property(type: PropertyType.date)
final DateTime dateTime;
@Backlink()
var products = ToMany<Product>();
double totalAmount;
PaymentStatus paymentStatus;
Pdf({
this.id = 0,
required this.pdfData,
required this.dateTime,
required this.customerName,
required this.totalAmount,
this.paymentStatus = PaymentStatus.unPaid,
});
int get status => paymentStatus.index;
set status(int value) {
paymentStatus = PaymentStatus.values[value];
}
}
@Entity()
class Product {
@Id()
int id;
String name;
String category;
int categoryId;
WeightType weightType;
double? price;
double weight;
bool isRefunded;
final pdf = ToOne<Pdf>();
Product({
this.id = 0,
required this.name,
required this.category,
required this.categoryId,
this.weightType = WeightType.kg,
this.price,
this.weight = 0,
this.isRefunded = false,
});
Product copy() => Product(
name: name,
category: category,
id: id,
price: price,
weight: weight,
weightType: weightType,
categoryId: categoryId,
isRefunded: isRefunded,
);
}
@override
int get hashCode => hashValues(
name.hashCode,
price.hashCode,
id.hashCode,
category.hashCode,
categoryId.hashCode,
weightType.hashCode,
weight.hashCode,
isRefunded.hashCode,
);
@override
bool operator ==(Object other) =>
other is Product &&
other.name == name &&
price == other.price &&
category == other.category &&
categoryId == other.categoryId &&
other.weight == weight &&
other.weightType == weightType &&
other.id == id;
}
this is how I'm putting it in the box,
void add(){
final billPdf = Pdf(
pdfData: pdf,
dateTime: DateTime.now(),
customerName: bill.customerName,
totalAmount: bill.totalAmount,
paymentStatus: bill.paymentStatus,
);
billPdf.products.addAll(bill.products);
DBService.pdfBox.put(billPdf,mode: obj.PutMode.put);
}
now when I try add same product in the box
, it removes the previous data from the list(db) and only adds the latest one so it is just updating the product. And if I change the PutMode
to insert
, it gives me exception. like this,
object put failed
I found this for kotlin, Can't save same data using ObjectBox with Android (Kotlin)
From this I even overrided the hashcode
and put some different value but it still removes previous values and also in my use case everything can be same.
So How can I put same objects in object-box?
The problem was that I didn't need to add final pdf = ToOne<Pdf>();
in product's Model and remove the @Backlink()
from Pdf
model. And it put data in different list and doesn't remove from previous list. And if you put duplicate object it just updates it.
Although I still have one problem it only stores default values which means some values might be null
but I think this problem is not related to question so it's fine and putting above as answer.