2017-10-07 51 views
0

我有2个模型用1:定义为这样的M相关联:Sequelize 1:m关联:set方法正在移除以前的关联?

var inventory = sequelize.define("Inventory",{**model definition**}; 
var trip = sequelize.define("Trip",{**model definition**}; 

Trip.hasMany("Inventory", {as:"Items"}); 
Inventory.belongsTo("Trip"); 

这创造了一个TRIPID在库存模型作为我计划。我在库存和旅行模型创建实例然后将它们使用这段代码相关联:

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); 
     }) 
    }) 
}) 

这工作,但每次我添加了一个新的项目,它关联到同一行,TRIPID从以前关联当新项目的tripId被设置时,项目被删除并变为空。我如何在我的库存模型中为多个项目使用setItems?提前致谢。

回答

0

这是正常的行为,因为你使用魔法设置方法(dbTrip setItems(dbItem)。)

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 

所以只需更换您的setItemsaddItems