NodeJS 使用Sequelize更新关联模型中的属性

xqk2d5yq  于 2023-06-22  发布在  Node.js
关注(0)|答案(2)|浏览(137)

是否可以一次性更新父模型和关联模型的属性?我很难让它工作,也找不到任何完整的例子。我不确定是我的代码出了什么问题,还是它没有按照我所期望的方式工作。我尝试添加onUpdate:“cascade”到我的hasMany定义,但这似乎没有做任何事情。
型号:

module.exports = function( sequelize, DataTypes ) {
var Filter = sequelize.define( 'Filter', {
    id : {
            type : DataTypes.INTEGER,
            autoIncrement : true,
            primaryKey : true
         },
        userId : DataTypes.INTEGER,
        filterRetweets : DataTypes.BOOLEAN,
        filterContent : DataTypes.BOOLEAN
    },
    {
        tableName : 'filter',
        timestamps : false
    }
);

var FilteredContent = sequelize.define( 'FilteredContent', {
        id : {
                type : DataTypes.INTEGER,
                autoIncrement : true,
                primaryKey : true
        },
        filterId : {
                        type : DataTypes.INTEGER,
                        references : "Filter",
                        referenceKey : "id"
        },
        content : DataTypes.STRING
    },
    {
        tableName : "filteredContent",
        timestamps : false
    }
);

Filter.hasMany( FilteredContent, { onUpdate : 'cascade', as : 'filteredContent', foreignKey : 'filterId' } );
sequelize.sync();

    return {
        "Filter" : Filter,
        "FilteredContent" : FilteredContent
    };
}

正在检索筛选器并尝试更新关联FilteredContent对象上的属性:

Filter.find({   where: { id: 3 }, 
            include: [ { model : FilteredContent, as : 'filteredContent' } ] 
}).success ( function( filter ) {
    var filteredContent = FilteredContent.build( {
        filterId : filter.id,
        id : 2,
        content : 'crap'
    });
    filter.save();
});

这将导致仅更新Filter对象中的属性。我如何让它也更新FilteredContent中的属性?
另外,定义模型后,sequelize.sync()是否需要?我不清楚它到底要做什么。我能够检索我的对象与关联没有它。我把它添加到我的代码中,以使更新工作,但我不确定它是否真的有必要。
谢谢

mklgxw1f

mklgxw1f1#

    • 针对您的问题:**

当您急切地加载FilteredContent(使用include)时,已经构建了一个模型示例,因此没有理由调用build。下面的代码应该可以满足您的要求:

Filter.find({
  where: { id: 3 }, 
  include: [ { model : FilteredContent, as : 'filteredContent' } ] 
}).then ( function( filter ) {
  return filter.filteredContent[0].updateAttributes({
    content: 'crap'
  })
}).then(function () {
  // DONE! :)
});
    • 关于你发布的整个代码的几个指针:**
  • sync为你的模型创建数据库表,如果它们不存在的话。如果表已经存在,则不需要执行此操作
  • sync是一个异步操作,因此不建议执行sequelize.sync而不附加回调。此外,看起来像是在模型定义中进行同步--应该只做一次,最好是在定义模型的地方。
  • 它看起来像是在一个文件中定义了几个模型-您应该在每个文件中只定义一个模型。可以通过在FilterContent文件中执行sequelize. import([path to filter model)来设置关联,或者在将模型导入应用的位置执行所有关联。
  • 编辑回复您的评论:*

您不能执行一个函数调用来同时更新filter和filteredcontent,但也不必按顺序执行更新。您可以发出所有更新命令,而无需等待更新命令完成。

Filter.find({
  where: { id: 3 }, 
  include: [ { model : FilteredContent, as : 'filteredContent' } ] 
}).then ( function( filter ) {
  return Promise.all([
    filter.updateAttributes({}),
    filter.filteredContent.map(fc => fc.updateAttributes({}))
  ]);
}).spread(function (filter, filteredContents) {

})

这样,所有的查询都将并行运行,当所有的查询都完成时,你的then函数将被调用。请注意,我在这里使用了spread,将从Promise.all返回的数组转换为单独的参数。

lf5gs5x2

lf5gs5x22#

使用@hatchifyjs/sequelize-create-with-associations,它就像这样简单:

await Filter.update({
  filteredContent: [
    { content: "x" },
    { content: "y" },
  ]
}, { where: { id: 3 } });

相关问题