在 Sequelize 中创建具有关联的实例 [英] Creating instance with an association in Sequelize

查看:35
本文介绍了在 Sequelize 中创建具有关联的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using Sequelize, I've created two models: User and Login.

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

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.

我如何一举.create一个带有用户关联的登录名?

How do I .create a Login with a User association all in one swoop?

当前代码(无效)

// 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

推荐答案

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

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
})

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

you can find more information here: http://docs.sequelizejs.com/manual/tutorial/associations.html#creating-with-associations

这篇关于在 Sequelize 中创建具有关联的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆