我正在使用node.js,Sequelize和MariaDB,我遇到以下错误,我不知道如何解决?
错误:命名属性“播放列表”与关联之间的冲突 模型playlist_entry上的“播放列表”。要解决此问题,请更改foreignKey 或者在你的协会定义中
我的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;
}
我的桌子:
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;
答案 0 :(得分:1)
在玩Sequelize时,我恰好遇到了这个问题,这是因为column name
和reference name
相同
实施错误
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;
};
这里column name
(menteeId
)和alias name
(menteeId
)是相同的,要解决此问题,您只需更改alias name
正确的实施
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;
};
您可以这样做
entities.PlaylistEntry.belongsTo(
entities.Playlist,
{
foreignKey: { name: 'fk_playlist' },
as: 'PlayListAlias', // Appropriate name
},
);