Reputation: 4047
I have the following tables:
class Occurrence extends Model {}
Occurrence.init({
date: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: Sequelize.NOW,
unique: 'uniqueOccurrence'
}
}, {
sequelize,
modelName: 'Occurrence'
});
class Event extends Model {}
Event.init({
title: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
sequelize,
modelName: 'Event'
});
With the following association:
Event.hasMany(Occurrence, { onDelete: 'CASCADE', foreignKey: { unique: 'uniqueOccurrence' } });
Occurrence.belongsTo(Event);
I am trying to have a composite unique constraint that would basically only fail when both occurrence.date
and Event.id
together are not unique.
The composite suppose to be on ``occurrence.EventIdnot
event.id`
However this for some reason fails.
Upvotes: 0
Views: 35
Reputation: 22813
If you wish to create an unique index with two fields and one of them is a foreign key you should define it explicitly to be able to indicate the same unique index name as indicated in the date
field:
EventId: {
type: DataTypes.INTEGER,
allowNull: false,
unique: 'uniqueOccurrence'
},
date: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: Sequelize.NOW,
unique: 'uniqueOccurrence'
}
and correct an association as well:
Event.hasMany(Occurrence, { onDelete: 'CASCADE', foreignKey: 'EventId' });
Occurrence.belongsTo(Event, { foreignKey: 'EventId' });
If you wish to use two fields as a foreign key then Sequelize cannot do this (and the foreignKey
option does not have the unique
prop).
Upvotes: 1