【问题标题】:Sequelize many to many documentation续集多对多文档
【发布时间】:2014-08-22 05:30:24
【问题描述】:

我正在尝试使用 node 和 sequelize 在项目和任务之间创建多对多关联。我无法弄清楚如何使用变量名创建新的“任务”,这些变量名可以作为 project.setTasks 函数的数组累积,因为这里的文档作为示例给出了很多细节缺失的例子。 http://sequelizejs.com/documentation#associations-many-to-many

这是他们给出的例子:

Project.hasMany(Task)
Task.hasMany(Project)

Project.create()...
Task.create()...
Task.create()...

// save them... and then:
project.setTasks([task1, task2]).success(function() {
// saved!

})

【问题讨论】:

    标签: node.js many-to-many sequelize.js


    【解决方案1】:

    我不确定你所说的“变量名”到底是什么意思。

    不过,here's 是 sequelize 测试套件中的一个示例,下面用我的 cmets 复制:

        // Define the models
        this.User = this.sequelize.define('User', { username: DataTypes.STRING });
        this.Task = this.sequelize.define('Task', { title: DataTypes.STRING, active: DataTypes.BOOLEAN });
    
        // Setup associations
        this.User.hasMany(this.Task);
        this.Task.hasMany(this.User);
    
        // using promises, sync the database, then create a user and two tasks
        return this.sequelize.sync({ force: true }).then(function() {
          return Promise.all([
            self.User.create({ username: 'John'}),
            self.Task.create({ title: 'Get rich', active: true}),
            self.Task.create({ title: 'Die trying', active: false})
          ]);
        }).spread(function (john, task1, task2) {
          // This line below is only relevant to the tests.
          self.tasks = [task1, task2];
    
          // Using the created (and saved) tasks and user, set the tasks and return the promise
          return john.setTasks([task1, task2]);
        });
    

    编辑我同意 sequelize 文档仍然太轻,但我发现它是迄今为止使用的一个很好的框架。如果有疑问,我建议您阅读单元测试,或者编写自己的测试来确认行为。

    编辑请注意,您也可以使用.addTask.removeTask,而不是简单地设置它们。见the docs

    【讨论】:

    • 你能在一个语句中同时执行插入和设置引用吗?
    • 不,我不这么认为。您需要使用如下所示的 Promise 以等待创建的任务存在于数据库中,然后再将它们设置给用户。
    • 看起来你可以在setTasks([task1, task2],{save:false})中做到这一点
    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 2015-05-16
    • 2019-08-08
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    相关资源
    最近更新 更多