mysql Sequelize:original:错误:当包含没有“attributes”字段的模型时,“field list”中的列“”未知

lo8azlld  于 2024-01-05  发布在  Mysql
关注(0)|答案(1)|浏览(287)

我试图使用Sequelize为MySQL查询,在我的代码中,我定义了我的模型,并将它们与他各自的关联联系起来。
尝试模拟一个音乐播放列表,有:艺术家,他们可以有多首歌曲。
播放列表,也有多首歌曲。
歌曲,它们是一个或多个播放列表的一部分,并且有一个或多个艺术家。
模型是这样定义的:
在每一个模型中,我定义了一个接口,其中包含各自的安全类型和舒适度字段
艺术家

  1. export interface IArtist {
  2. ID_ARTIST: number,
  3. NAME: string
  4. }
  5. export const Artist = seq.define<Model<IArtist>>("Artist", {
  6. ID_ARTIST: {
  7. primaryKey: true,
  8. type: DataTypes.INTEGER,
  9. allowNull: false,
  10. autoIncrement: true
  11. },
  12. NAME: DataTypes.STRING(30)
  13. }, {
  14. timestamps: true,
  15. createdAt: true,
  16. updatedAt: false,
  17. tableName: "ARTISTS",
  18. })

字符串
播放列表

  1. export interface IPlaylist {
  2. ID_PLAYLIST: number,
  3. NAME: string
  4. }
  5. export const PlayList = seq.define<Model<IPlaylist>>("Playlist", {
  6. ID_PLAYLIST: {
  7. primaryKey: true,
  8. type: DataTypes.INTEGER,
  9. allowNull: false,
  10. autoIncrement: true,
  11. },
  12. NAME: DataTypes.STRING(20)
  13. }, {
  14. timestamps: true,
  15. createdAt: true,
  16. updatedAt: false,
  17. tableName: "PLAYLISTS"
  18. })


  1. export interface ISong {
  2. ID_SONG: number,
  3. ID_ARTIST: number,
  4. ID_PLAYLIST: number,
  5. DURATION: number,
  6. NAME: string
  7. }
  8. export const Song = seq.define<Model<ISong>>("Song", {
  9. ID_SONG: {
  10. primaryKey: true,
  11. type: DataTypes.INTEGER,
  12. allowNull: false,
  13. autoIncrement: true
  14. },
  15. ID_ARTIST: {
  16. type: DataTypes.INTEGER,
  17. references: {
  18. model: Artist,
  19. key: "ID_ARTIST"
  20. }
  21. },
  22. ID_PLAYLIST: {
  23. type: DataTypes.INTEGER,
  24. references: {
  25. model: PlayList,
  26. key: "ID_PLAYLIST"
  27. }
  28. },
  29. DURATION: DataTypes.INTEGER,
  30. NAME: DataTypes.STRING(40)
  31. }, {
  32. timestamps: true,
  33. updatedAt: false,
  34. tableName: "SONGS"
  35. })


以及各表的关系:

  1. Artist.hasMany(Song)
  2. PlayList.hasMany(Song)
  3. Song.belongsTo(Artist, { foreignKey: "ID_ARTIST" })
  4. Song.belongsTo(PlayList, { foreignKey: "ID_PLAYLIST" })


然后当我尝试像这样执行'findAll'操作时:

  1. const query = await Song.findAll({
  2. include: {
  3. model: Artist,
  4. required: true
  5. },
  6. where: {
  7. ID_ARTIST: idArtist
  8. }
  9. })


idArtist是一个函数参数-> idArtist:string
我得到下一个错误:sqlMessage:“Unknown column 'Song.ArtistIDARTIST' in 'field list'”
而sequelize:sql的查询结果是:“选择Song . ID_SONGSong . ID_ARTISTSong . ID_PLAYLISTSong . DURATIONSong . NAMESong . createdAtSong . ArtistIDARTISTSong . PlaylistIDPLAYLISTArtist . ID_ARTIST AS Artist.ID_ARTISTArtist . NAME AS Artist.NAMEArtist. createdAt AS Artist.createdAtSONGS AS Song内部连接ARTISTS AS Artist ON Song. ID_ARTIST = Artist. ID_ARTIST其中Song. ID_ARTIST = '1';”
为什么sequelize在findAll或类似方法中不使用“attributes”字段时试图获取不存在的列,如Song.PlaylistIDPLAYLIST或Song.ArtistIDARTIST
谢谢你,如果需要其他信息,请告诉我:)

4ioopgfo

4ioopgfo1#

您只需要使用相同的foreignKey选项定义配对关联,请参阅我的answer here

相关问题