node.js 在 Sequelize 中创建具有关联的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29995868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating instance with an association in Sequelize
提问by slifty
Using Sequelize, I've created two models: Userand Login.
使用Sequelize,我创建了两个模型:User和Login。
Users can have more than one Login, but a login must have exactly one user, which means a Login cannot be saved without a User ID.
用户可以有多个登录名,但一个登录名必须只有一个用户,这意味着没有用户 ID 无法保存登录名。
How do I .createa Login with a User association all in one swoop?
如何.create一键登录用户关联?
Current Code (Doesn't Work)
当前代码(不起作用)
// 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')
});
)};
The above results in SequelizeValidationError: notNull Violation: UserId cannot be null
以上结果在 SequelizeValidationError: notNull Violation: UserId cannot be null
回答by Arwed Mett
Assuming you have the right association between users and login, you can just create a user including a login:
假设您在用户和登录名之间有正确的关联,您可以创建一个包含登录名的用户:
User.create({
name: "name",
Login: {...}
},{
include: Login
})
you can find more information here: http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations
您可以在此处找到更多信息:http: //docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations
回答by Matheus Dal'Pizzol
First of all you need to setup the relations in both ways, like this:
首先,您需要以两种方式设置关系,如下所示:
// Set up the models
var User = sequelize.define('User', {});
var Login = sequelize.define('Login', {});
// Set the correct associations
User.hasMany(Login, {})
Login.belongsTo(User, {});
Then, you need to properly get the instances returned by the promises:
然后,您需要正确获取 promise 返回的实例:
// 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
});
回答by Calvintwr
In your .then, the callback receives the model instance created by the previous call. You need to specify the argument inside the callback function.
在您的 中.then,回调接收由前一个调用创建的模型实例。您需要在回调函数中指定参数。
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.
});
Also something important I would like to point out is your missing varstatements! Those are important but not related to this question. See Declaring variables without var keyword
还有一点我想指出的是你遗漏的var陈述!这些很重要,但与这个问题无关。请参阅在没有 var 关键字的情况下声明变量
回答by Kshateesh
An Update to @Arwed Mett's answer
@Arwed Mett 答案的更新
//Create Association Alias or just setting association alias by using 'as' keyword will also work
Login.User = Login.belongsTo(User);
User.create({
name: "name",
Login: {...}
}, {
include: [{
association: Login.User
}]
});
Refrence link - http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations
参考链接 - http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations
回答by Achille Skineur
You have association between User an Login with constraint allowNull at false. You must create Login before User or set allowNull at true in model and the table to DB (LoginId Null constraint)
您在 User 和 Login 之间具有关联,约束条件为 allowNull 为 false。您必须在 User 之前创建 Login 或将模型中的 allowNull 设置为 true 并将表设置为 DB(LoginId Null 约束)
var User = sequelize.define('User', {});
var Login = sequelize.define('Login', {});
Login.belongsTo(User, {
onDelete: 'cascade',
foreignKey: {
field: 'userId',
allowNull: false,
}
});
Solution
解决方案
Login.create({
username: "username",
User: {...}
},{
include: User
})
回答by iwaduarte
As an extra you could also nest your creation to be even more effective and concise.
另外,您还可以嵌套您的创作,使其更加有效和简洁。
// Set up the models
var User = sequelize.define('User', {});
var Login = sequelize.define('Login', {});
...
User.create({
name: "name",
Login:
{
users: {..i.e several users if a user belongs to another user..}
}
},{
include:{
model: Login,
include: User //nested model.Create
}
})
as seen here: https://github.com/sequelize/sequelize/issues/7252
回答by Quy Tang
I have the same issue recently!
I have a typo mistake with the foreignKey config. Use fieldinstead of namecaused the issue.
我最近也有同样的问题!我的外键配置有一个拼写错误。使用field而不是name导致问题。
The change below will fix it.
下面的更改将修复它。
{
foreignKey: {
name: 'userId',
allowNull: false,
}
}

