gpt4 book ai didi

sequelize.js - Sequelize 多对多错误 : user. addProjects is not a function

转载 作者:行者123 更新时间:2023-12-03 22:23:50 25 4
gpt4 key购买 nike

我正在尝试使用 sequelize 创建多对多关系,但每次我尝试使用此函数时:

    user.addProject(project, { through: { status: 'started' }})

我的服务器崩溃了,我收到这个错误:

user.addProjects is not a function at User.create.then.user


 var connection = new Sequelize('database', 'root', 'phase_99');

var User = connection.define('user', {title: Sequelize.STRING});
var Project = connection.define('project', {title: Sequelize.STRING});
var UserProjects = connection.define('userProjects', {
status: Sequelize.STRING
})

User.belongsToMany(Project, {as: 'Workers', through: UserProjects, foreignKey: 1 })
Project.belongsToMany(User, { as: 'Tasks', through: UserProjects, foreignKey: 1 })


connection.sync().then(() => {
var project = Project.create({title: 'ISD Corp'})

User.create()
.then(user => {

user.addProject(project, { through: { status: 'started' }})

})
});

我不确定我做错了什么,我遵循了文档,并且这个函数应该是自动生成的

最佳答案

sync() 后的代码应如下所示

connection.sync().then(() => {
Project.create({ title: 'ISD Corp' }).then((project) => {
User.create().then((user) => {
user.addTask(project, { status: 'started' }).then(() => {
// finished
});
});
});
});

由于您在 as 中使用了 belongsToMany 属性,因此您向用户添加项目的方法现在称为 addTaskaddTasks (如果同时有多个任务)。

在您的代码中, project 变量是您尝试在 Promise 方法中使用的 addProject 实例 - 这是它不起作用的第一个原因。其次,在 addProject 中为了给join table 添加额外的属性,你不需要使用 through 对象。

关于sequelize.js - Sequelize 多对多错误 : user. addProjects is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42516589/

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