我正在尝试使用 Node 和 Sequelize 在项目和任务之间创建多对多关联。我无法弄清楚如何使用变量名称创建新的“任务”,这些变量名称可以累积为项目的数组。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!
})
最佳答案
我不确定“变量名称”到底是什么意思。
但是,here's Sequelize 测试套件中的一个示例,复制如下并附有我的评论:
// 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
关于node.js - 序列化多对多文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20341193/