Reputation: 13
I have 2 models with a 1:M association defined as such:
var inventory = sequelize.define("Inventory",{**model definition**};
var trip = sequelize.define("Trip",{**model definition**};
Trip.hasMany("Inventory", {as:"Items"});
Inventory.belongsTo("Trip");
This created a Tripid in the inventory model as I planned. I create instances in the Inventory and Trip models then associate them using this bit of code:
app.post('/api/trip/inventory/new/:trip_id', function(req,res){
var new_item = req.body;
var trip_id = req.params.trip_id;
db.Inventory.create(new_item).then(dbItem => {
db.Trip.findOne({
where : {id:trip_id}
}).then(dbTrip =>{
dbTrip.setItems(dbItem);
res.json(dbItem);
})
})
})
This works, but each time I add a new item and associate it to the same trip, the tripId from the previously associated item is removed and becomes null as the tripId for the new item is set. How do i use setItems for multiple items in my Inventory model? Thanks in advance.
Upvotes: 1
Views: 650
Reputation: 351
This is normal behaviour, because you use magic set method (dbTrip.setItems(dbItem))
From API References:
user.addPicture(p) // Add a single picture
user.setPictures([p1, p2]) // Associate user with ONLY these two picture, all other associations will be deleted
user.addPictures([p1, p2]) // Associate user with these two pictures, but don't touch any current associations
So just replace your setItems to addItems
Upvotes: 1