在Sequelize中使用关联创build实例
使用Sequelize ,我创build了两个模型: User
和Login
。
用户可以有多个login,但login必须只有一个用户,这意味着如果没有用户标识,则不能保存login。
我如何用一个用户协会一举.create
一个login?
当前代码(不起作用)
// Set up the models var User = sequelize.define('User', {}); var Login = sequelize.define('Login', {}); Login.belongsTo(User, { onDelete: 'cascade', foreignKey: { field: 'userId', allowNull: false, } }); // Create the instances var user = User.create().then(function() { // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION var login = Login.create({ userId: user.get('id') }); )};
SequelizeValidationError: notNull Violation: UserId cannot be null
的上述结果SequelizeValidationError: notNull Violation: UserId cannot be null
在你的.then
,callback接收由前一个调用创build的模型实例。 您需要在callback函数中指定参数。
var user = User.create().then(function(user) { // THIS IS WHERE I WOULD LIKE TO SET THE ASSOCIATION var login = Login.create({ userId: user.get('id') }); return login }).then(function(login) { // all creation are complete. do something. });
另外一些重要的我想指出的是你的遗漏var
语句! 这些是重要的,但不涉及这个问题。 请参阅声明无var关键字的variables
假设你有正确的用户和login关系,你可以创build一个包括login用户:
User.create({ name: "name", Login: {...} },{ include: Login })
你可以在这里find更多的信息: http : //docs.sequelizejs.com/en/v3/docs/associations/#creating-elements-of-a-belongsto-or-hasone-association
首先,你需要以这两种方式build立关系:
// Set up the models var User = sequelize.define('User', {}); var Login = sequelize.define('Login', {}); // Set the correct associations User.hasMany(Login, {}) Login.belongsTo(User, {});
然后,您需要正确地获取承诺返回的实例:
// Create the instances User.create({}).then(function(newUser) { // now you can use newUser acessors to create the login return newUser.createLogin({}); ).then(function(newLogin){ // newLogin }).catch(function(error){ // error });
我最近有同样的问题! 我有一个外键configuration错字。 使用field
而不是name
导致了问题。
以下更改将修复它。
{ foreignKey: { name: 'userId', allowNull: false, } }