Repository navigation
Closed
Description
I have a join table for a many-to-many relationship that is defined as:
class OrganizationUser extends Sequelize.Model {
static init(sequelize) {
return super.init({
organizationId: {
type: Sequelize.INTEGER,
allowNull: false,
validate: {
notEmpty: true,
min: 1
},
field: 'organization_id'
},
userId: {
type: Sequelize.INTEGER,
allowNull: false,
validate: {
notEmpty: true,
min: 1
},
field: 'user_id'
}
}, {
sequelize, tableName: 'organization_user', underscored: true
})
};
static associate(models) {
this.belongsTo(models.Organization, {
foreignKey: 'organization_id'
});
this.belongsTo(models.User, {
foreignKey: 'user_id'
});
}
}
When I try to create a new entry like this, it fails because organization_id and user_id are set to null by Sequelize:
OrganizationUser.create({
userId: req.user.id,
organizationId: organization.id
});
After digging around, I determined it's because the primary fields for the instance are set here by model.js:
// set id to null if not passed as value, a newly created dao has no id
// removing this breaks bulkCreate
// do after default values since it might have UUID as a default value
if (this.constructor.primaryKeyAttributes.length) {
this.constructor.primaryKeyAttributes.forEach(primaryKeyAttribute => {
if (!defaults.hasOwnProperty(primaryKeyAttribute)) {
defaults[primaryKeyAttribute] = null;
}
});
}
In utils.js, the camelcased fields that I provide to the .create() function are set to null by this function because it only checks for undefined:
/* Used to map field names in values */
function mapValueFieldNames(dataValues, fields, Model) {
const values = {};
for (const attr of fields) {
if (dataValues[attr] !== undefined && !Model._virtualAttributes.has(attr)) {
// Field name mapping
if (Model.rawAttributes[attr] && Model.rawAttributes[attr].field && Model.rawAttributes[attr].field !== attr) {
values[Model.rawAttributes[attr].field] = dataValues[attr];
} else {
values[attr] = dataValues[attr];
}
}
}
return values;
}
The current workaround is to not use the "field" Model option or to add a different primary key column.
Metadata
Metadata
Assignees
Labels
No labels
Activity
papb commentedon Jul 25, 2019
Closing in favor of #11225.
When #11225 gets closed, if anyone thinks this particular issue is still an issue, please ping me.