gpt4 book ai didi

sequelize.js - Sequelize 1 :m associations: set method is removing previous associations?

转载 作者:行者123 更新时间:2023-12-03 22:20:04 29 4
gpt4 key购买 nike

我有 2 个具有 1:M 关联的模型,定义如下:

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

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

这按照我的计划在库存模型中创建了一个 Tripid。我在 Inventory 和 Trip 模型中创建实例,然后使用以下代码将它们关联起来:
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 时变为 null。如何将 setItems 用于库存模型中的多个项目?提前致谢。

最佳答案

这是正常行为,因为您使用了魔法 set 方法 (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

所以只需将您的 setItems 替换为 addItems

关于sequelize.js - Sequelize 1 :m associations: set method is removing previous associations?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46617135/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com