gpt4 book ai didi

javascript - Sequelize : Naming collision between attribute 'playlist' and association 'playlist' ?

转载 作者:行者123 更新时间:2023-12-03 12:42:33 27 4
gpt4 key购买 nike

我正在使用 node.js、Sequelize 和 MariaDB,我遇到了以下错误,我不确定如何解决?

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



我的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;
}

我的 table :
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;

最佳答案

我在玩 Sequelize 时遇到了这个问题,这是因为 column namereference 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
},
);

关于javascript - Sequelize : Naming collision between attribute 'playlist' and association 'playlist' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37121882/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com