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

lo8azlld  于 12个月前  发布在  Mysql
关注(0)|答案(1)|浏览(206)

我试图使用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_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

相关问题