不要怂,就是干,撸起袖子干!

Commit 3fbd5316 by Scott BonAmi Committed by Sushant

fix(create): allow foreign key to be null when association reference is set (#9466)

1 parent bce3d9aa
......@@ -6,6 +6,7 @@ const Utils = require('./utils');
const sequelizeError = require('./errors');
const Promise = require('./promise');
const DataTypes = require('./data-types');
const BelongsTo = require('./associations/belongs-to');
const _ = require('lodash');
/**
......@@ -320,6 +321,8 @@ class InstanceValidator {
*/
_validateSchema(rawAttribute, field, value) {
if (rawAttribute.allowNull === false && (value === null || value === undefined)) {
const association = _.values(this.modelInstance.constructor.associations).find(association => association instanceof BelongsTo && association.foreignKey === rawAttribute.fieldName);
if (!association || !this.modelInstance.get(association.associationAccessor)) {
const validators = this.modelInstance.validators[field];
const errMsg = _.get(validators, 'notNull.msg', `${this.modelInstance.constructor.name}.${field} cannot be null`);
......@@ -332,6 +335,7 @@ class InstanceValidator {
'is_null'
));
}
}
if (rawAttribute.type === DataTypes.STRING || rawAttribute.type instanceof DataTypes.STRING || rawAttribute.type === DataTypes.TEXT || rawAttribute.type instanceof DataTypes.TEXT) {
if (Array.isArray(value) || _.isObject(value) && !(value instanceof Utils.SequelizeMethod) && !Buffer.isBuffer(value)) {
......
......@@ -60,6 +60,39 @@ describe(Support.getTestDialectTeaser('Model'), () => {
});
});
it('should create data for BelongsTo relations with no nullable FK', function () {
const Product = this.sequelize.define('Product', {
title: Sequelize.STRING
});
const User = this.sequelize.define('User', {
first_name: Sequelize.STRING
});
Product.belongsTo(User, {
foreignKey: {
allowNull: false
}
});
return this.sequelize.sync({ force: true }).then(() => {
return Product.create({
title: 'Chair',
User: {
first_name: 'Mick'
}
}, {
include: [{
model: User
}]
}).then(savedProduct => {
expect(savedProduct).to.exist;
expect(savedProduct.title).to.be.equal('Chair');
expect(savedProduct.User).to.exist;
expect(savedProduct.User.first_name).to.be.equal('Mick');
});
});
});
it('should create data for BelongsTo relations with alias', function() {
const Product = this.sequelize.define('Product', {
title: Sequelize.STRING
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!