我试图使用Sequelize为MySQL查询,在我的代码中,我定义了我的模型,并将它们与他各自的关联联系起来。
尝试模拟一个音乐播放列表,有:艺术家,他们可以有多首歌曲。
播放列表,也有多首歌曲。
歌曲,它们是一个或多个播放列表的一部分,并且有一个或多个艺术家。
模型是这样定义的:
在每一个模型中,我定义了一个接口,其中包含各自的安全类型和舒适度字段
艺术家
export interface IArtist {
ID_ARTIST: number,
NAME: string
}
export const Artist = seq.define<Model<IArtist>>("Artist", {
ID_ARTIST: {
primaryKey: true,
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true
},
NAME: DataTypes.STRING(30)
}, {
timestamps: true,
createdAt: true,
updatedAt: false,
tableName: "ARTISTS",
})
字符串
播放列表
export interface IPlaylist {
ID_PLAYLIST: number,
NAME: string
}
export const PlayList = seq.define<Model<IPlaylist>>("Playlist", {
ID_PLAYLIST: {
primaryKey: true,
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
},
NAME: DataTypes.STRING(20)
}, {
timestamps: true,
createdAt: true,
updatedAt: false,
tableName: "PLAYLISTS"
})
型
宋
export interface ISong {
ID_SONG: number,
ID_ARTIST: number,
ID_PLAYLIST: number,
DURATION: number,
NAME: string
}
export const Song = seq.define<Model<ISong>>("Song", {
ID_SONG: {
primaryKey: true,
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true
},
ID_ARTIST: {
type: DataTypes.INTEGER,
references: {
model: Artist,
key: "ID_ARTIST"
}
},
ID_PLAYLIST: {
type: DataTypes.INTEGER,
references: {
model: PlayList,
key: "ID_PLAYLIST"
}
},
DURATION: DataTypes.INTEGER,
NAME: DataTypes.STRING(40)
}, {
timestamps: true,
updatedAt: false,
tableName: "SONGS"
})
型
以及各表的关系:
Artist.hasMany(Song)
PlayList.hasMany(Song)
Song.belongsTo(Artist, { foreignKey: "ID_ARTIST" })
Song.belongsTo(PlayList, { foreignKey: "ID_PLAYLIST" })
型
然后当我尝试像这样执行'findAll'操作时:
const query = await Song.findAll({
include: {
model: Artist,
required: true
},
where: {
ID_ARTIST: idArtist
}
})
型
idArtist是一个函数参数-> idArtist:string
我得到下一个错误:sqlMessage:“Unknown column 'Song.ArtistIDARTIST' in 'field list'”
而sequelize:sql的查询结果是:“选择Song
. ID_SONG
,Song
. ID_ARTIST
,Song
. ID_PLAYLIST
,Song
. DURATION
,Song
. NAME
,Song
. createdAt
,Song
. ArtistIDARTIST
,Song
. PlaylistIDPLAYLIST
,Artist
. ID_ARTIST
AS Artist.ID_ARTIST
,Artist
. NAME
AS Artist.NAME
,Artist
. createdAt
AS Artist.createdAt
从SONGS
AS Song
内部连接ARTISTS
AS Artist
ON Song
. ID_ARTIST
= Artist
. ID_ARTIST
其中Song
. ID_ARTIST
= '1';”
为什么sequelize在findAll或类似方法中不使用“attributes”字段时试图获取不存在的列,如Song.PlaylistIDPLAYLIST或Song.ArtistIDARTIST
谢谢你,如果需要其他信息,请告诉我:)
1条答案
按热度按时间4ioopgfo1#
您只需要使用相同的
foreignKey
选项定义配对关联,请参阅我的answer here