I am using node.js, Sequelize and MariaDB and I am running into the following error, which I am not sure how to resolve?
Error: Naming collision between attribute 'playlist' and association 'playlist' on model playlist_entry. To remedy this, change either foreignKey or as in your association definition
My Javascript:
Entities = function (settings, context) {
sequelize = context.sequelize;
var entities = {
Playlist: this.sequelize.define('playlist', {
name: Sequelize.STRING,
description: Sequelize.STRING
}),
PlaylistEntry: this.sequelize.define('playlist_entry', {
playlist: Sequelize.INTEGER
//track: Sequelize.INTEGER
})
};
entities.PlaylistEntry.belongsTo(
entities.Playlist,
{ foreignKey: { name: 'fk_playlist' }});
return entities;
}
My tables:
CREATE TABLE `playlist` (
`id` int(11) unsigned NOT NULL,
`name` varchar(255) NOT NULL,
`description` varchar(255) DEFAULT NULL,
`createdAt` timestamp NULL DEFAULT NULL,
`updatedAt` timestamp NULL DEFAULT NULL,
`external_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `playlist_entry` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`playlist` int(11) unsigned DEFAULT NULL,
`track` int(11) unsigned DEFAULT NULL,
`createdAt` timestamp NULL DEFAULT NULL,
`updatedat` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `track_idx` (`track`),
KEY `playlist_idx` (`playlist`),
CONSTRAINT `fk_playlist` FOREIGN KEY (`playlist`) REFERENCES `playlist` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
I faced exactly this problem while play with Sequelize, It's happened because the column name
and reference name
are same
Wrong Implementation
module.exports = (sequelize, DataTypes) => {
const session = sequelize.define('session', {
menteeId: DataTypes.INTEGER,
}, {});
session.associate = (models) => {
session.belongsTo(models.user, {
foreignKey: 'menteeId',
as: 'menteeId',
onDelete: 'CASCADE',
});
};
return session;
};
Here the column name
(menteeId
) and alias name
(menteeId
) are the same, To resolve this you just need to change alias name
Correct Implementation
module.exports = (sequelize, DataTypes) => {
const session = sequelize.define('session', {
menteeId: DataTypes.INTEGER,
}, {});
session.associate = (models) => {
session.belongsTo(models.user, {
foreignKey: 'menteeId',
as: 'MenteeId', // Changes applied here
onDelete: 'CASCADE',
});
};
return session;
};
In your case, you can do this
entities.PlaylistEntry.belongsTo(
entities.Playlist,
{
foreignKey: { name: 'fk_playlist' },
as: 'PlayListAlias', // Appropriate name
},
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With