Creating instance with an association in Sequelize

后端 未结 8 1021
清酒与你
清酒与你 2021-02-02 09:09

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

Users can have more than one Login, but a login must have exactly one user, which me

8条回答
  •  不知归路
    2021-02-02 09:38

    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)

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

提交回复
热议问题