Sequelize通过关联创建

use*_*142 3 associations node.js sequelize.js

我正在为两个类之间的关联开发一个create方法.sequelize文档表明这可以使用包括一步完成

IntramuralAthlete.create(intramuralAthlete,{
         include: [Person]
    }).then((data,err)=>{
         if(data)res.json(data);
         else res.status(422).json(err);
    }).catch(function(error) {
         res.status(422).json({message: "failed to create athlete", error: error.message});
});
Run Code Online (Sandbox Code Playgroud)

我的模型关联看起来像这样

var Person = require('../models').person;
var IntramuralAthlete = require('../models').intramuralAthlete;

IntramuralAthlete.belongsTo(Person);
Run Code Online (Sandbox Code Playgroud)

当我登录时,校内运动员的价值是

{ 
   person: 
   { firstName: 'Test',
     lastName: 'User',
     email: 'test@user.com'
  },
  grade: '12th',
  organizationId: 1 
}
Run Code Online (Sandbox Code Playgroud)

但是我得到了错误notNull Violation: personId cannot be null.这个错误让我觉得Sequelize表示我打算在同一个调用中创建personId的方式听起来有些不对劲.

我在create语句中指示使用IntramuralAthlete创建的关联表的方式是否有问题?

谢谢!

编辑:我也试过以下结构,结果相同

{ 
  Person: { 
    firstName: 'Test',
    lastName: 'User',
    email: 'test@user.com'
 },
 grade: '12th',
 organizationId: 1 
}
Run Code Online (Sandbox Code Playgroud)

我的模型如下:

module.exports = function(sequelize, DataTypes) {
  return sequelize.define('intramuralAthlete', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: sequelize.literal('CURRENT_TIMESTAMP')
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: sequelize.literal('CURRENT_TIMESTAMP')
    },
    grade: {
      type: DataTypes.STRING,
      allowNull: true
    },
    age: {
      type: DataTypes.INTEGER(11),
      allowNull: true
    },
    school: {
      type: DataTypes.STRING,
      allowNull: true
    },
    notes: {
      type: DataTypes.STRING,
      allowNull: true
    },
    guardianId: {
      type: DataTypes.INTEGER(11),
      allowNull: true,
      references: {
        model: 'contact',
        key: 'id'
      }
    },
    personId: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'person',
        key: 'id'
      }
    },
    mobileAthleteId: {
      type: DataTypes.INTEGER(11),
      allowNull: true,
      references: {
        model: 'mobileAthlete',
        key: 'id'
      }
    },
    organizationId: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'organization',
        key: 'id'
      }
    }
  }, {
    tableName: 'intramuralAthlete'
  });
};
Run Code Online (Sandbox Code Playgroud)

pio*_*ias 6

我想,你的模型命名PersonIntramuralAthlete(第一参数sequelize.define方法).在这种情况下,当您创建类似于您的关联,并且未定义as属性时,您的create数据对象应如下所示

{
    Person: {
        firstName: 'Test',
        lastName: 'User',
        email: 'test@user.com'
    },
    grade: '12th',
    organizationId: 1 
}
Run Code Online (Sandbox Code Playgroud)

如果您想要使用person(就像在代码中一样),您应该稍微有点不同地定义关联

IntramuralAthlete.belongsTo(Person, { as: 'person' });
Run Code Online (Sandbox Code Playgroud)

然后,您必须在类似createinclude属性中执行查询中的一些更改options

IntramuralAthlete.create(data, {
    include: [
        { model: Person, as: 'person' }
    ]
}).then((result) => {
    // both instances should be created now
});
Run Code Online (Sandbox Code Playgroud)

编辑:save()用空值哄骗方法personId

allowNull: false如果你这样做,你可以保持

{
    person: {
        // person data
    },
    personId: '', // whatever value - empty string, empty object etc.
    grade: '12th',
    organizationId: 1
}
Run Code Online (Sandbox Code Playgroud)

编辑2:创建时禁用验证.

此案例假定验证已关闭.省略模型验证似乎是一个坏主意,但是仍然维护数据库表级验证 - 在迁移中定义,它仍然可以检查是否personId设置了值

IntramuralAthlete.create(data, {
    include: [
        { model: Person, as: 'person' }
    ],
    validate: false
}).then((result) => {
    // both instances should be created now
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,data对象可以在您的示例中 - 没有personId属性.我们省略了允许传递null值的模型级验证,但是如果在save()方法期间它仍然是null值 - 数据库级验证会抛出错误.