【发布时间】:2017-07-21 02:27:26
【问题描述】:
我正在为两个类之间的关联创建一个方法。 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});
});
我的模型关联是这样的
var Person = require('../models').person;
var IntramuralAthlete = require('../models').intramuralAthlete;
IntramuralAthlete.belongsTo(Person);
我登录时校内运动员的价值是
{
person:
{ firstName: 'Test',
lastName: 'User',
email: 'test@user.com'
},
grade: '12th',
organizationId: 1
}
但我收到错误 notNull Violation: personId cannot be null。这个错误听起来像是我向 Sequelize 指示我打算在同一个调用中创建 personId 的方式有问题。
我向create 语句指示要与 IntramuralAthlete 创建哪些关联表的方式有问题吗?
谢谢!
编辑: 我也尝试过以下结构,结果相同
{
Person: {
firstName: 'Test',
lastName: 'User',
email: 'test@user.com'
},
grade: '12th',
organizationId: 1
}
我的模型如下:
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'
});
};
【问题讨论】:
标签: node.js associations sequelize.js