在Sequelize中使用关联创建实例

sli*_*fty 22 node.js sequelize.js

使用Sequelize,我创建了两个模型:UserLogin.

用户可以有多个登录,但登录必须只有一个用户,这意味着没有用户ID就无法保存登录.

如何.create一次性登录用户关联?

当前代码(不起作用)

// 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')
  });

)};
Run Code Online (Sandbox Code Playgroud)

以上结果 SequelizeValidationError: notNull Violation: UserId cannot be null

Arw*_*ett 57

假设您在用户和登录之间拥有正确的关联,您可以创建一个包含登录的用户:

User.create({
   name: "name",
   Login: {...}
},{
   include: Login
})
Run Code Online (Sandbox Code Playgroud)

你可以在这里找到更多信息:http: //docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations

  • 链接已过时.我相信现在的(至少现在)是:http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations (5认同)
  • 有没有办法为bulkCreate() 做到这一点? (2认同)

Mat*_*zol 15

首先,您需要以两种方式设置关系,如下所示:

// Set up the models
var User = sequelize.define('User', {});
var Login = sequelize.define('Login', {});

// Set the correct associations
User.hasMany(Login, {})
Login.belongsTo(User, {});
Run Code Online (Sandbox Code Playgroud)

然后,您需要正确获取promises返回的实例:

// 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
});
Run Code Online (Sandbox Code Playgroud)


Cal*_*twr 6

在您.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.
});
Run Code Online (Sandbox Code Playgroud)

另外一件重要的事情我想指出的是你遗漏的var陈述!这些很重要,但与这个问题无关.请参见声明不带var关键字的变量


Ksh*_*esh 5

@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
  }]
});
Run Code Online (Sandbox Code Playgroud)

参考链接 - http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations