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

标签 sequelize.js

我有 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/

相关文章:

node.js - 如何在 Sequelize 模型中设置特定列的排序规则?

node.js - 如何在 Sequelize 中仅禁用 updatedAt 字段?

mysql - 先按完全匹配顺序对 Op.or order 进行 Sequelize

javascript - Expressjs 同步/异步中间件问题——如何解决?

javascript - 为 Sequelize 创建中间 BaseModel 类

mysql - Sequelize.js:包括意外。元素必须是模型、关联或对象

javascript - 如何计算表中的行数?

sequelize.js - 如何使用 Sequelize ORM `include` 同一模型的两个单独引用?

mysql - 从 Sequelize 中的其他表查找计数

node.js - Node and sequelize -> .catch(...) 没有按预期工作