Reputation: 616
I have two models, items and order, that have a many-to-many association. What I've been trying to do for the past 5 hours is figure out a way to add multiple items objects to an order including duplicates.
If the items are unique it works perfectly fine, but if I try something like this:
order.items.add([12, 13, 12, 12]);
order.save();
It will only save 12, 13. The duplicates will be ignored, not so good if you want to order more than one of any item.
Any suggestions would be helpful.
Upvotes: 3
Views: 267
Reputation: 119
One way is to go with creating a new model for maintaining the many-to-many association but another way would be adding a column in your Order model called "Quantity" and increment it whenever you're adding the same item again.
Upvotes: 0
Reputation: 2051
Many-to-many association in DB scheme is creating relation between any record from a table to any record to another table, of course it always unique, because 12
is already has an association with that order
record.
The solution is, use extra model to achieve that. For example, in models
folder:
module.exports = {
attributes: {
items : {collection: 'OrderItem', via: 'order'}
}
};
module.exports = {
attributes: {
order : {model: 'Order'},
item : {model: 'Item'}
}
};
module.exports = {
attributes: {
}
};
So from Order
model, you can add some OrderItem
that is a model that represent relation between Order
and Item
, and OrderItem
is unique in Order
point of view though an Item under it's record may be same.
Upvotes: 2