简体   繁体   中英

How to prevent Sequelize adding 'Id' to column name?

I am finding when I do a query with Sequelize 'Id' is being added to the end of my column name, but I am not sure how to instruct Sequelize not to do so?

I have created an entity data Model for Sequelize, as follows:

function initializeDataModel(sequelize) {
    var dataModel = { };    

    dataModel.Playlist = this.sequelize.define('playlist', {
        name: Sequelize.STRING,
    }); 

    dataModel.PlaylistEntry = this.sequelize.define('playlist_entry', {
        playlist: {
            name: 'playlist',
            type: Sequelize.INTEGER,
            references: {
                // This is a reference to another model
                model: dataModel.Playlist,

                // This is the column name of the referenced model
                key: 'id'

                // This declares when to check the foreign key constraint. PostgreSQL only.
                //deferrable: Sequelize.Deferrable.INITIALLY_IMMEDIATE 
            }               
        },
        track: Sequelize.INTEGER
    });                

    dataModel.PlaylistEntry.belongsTo(
         dataModel.Playlist,
         { as: 'Playlist', foreignKey: { name: 'playlist' }});

    dataModel.Playlist.hasMany(dataModel.PlaylistEntry);

    return dataModel;
}    

The fields in the 'playlist_entry' table (in MariaDB) are as follows:

  • id: INT(11)
  • playlist: INT(11)
  • track: INT(11)

The query I am performing is as follows:

    eagerIncludes.push(this.dataModel.PlaylistEntry);

    this.dataModel.Playlist.find({
       where: { id: playlistId },
       limit: limit,
       offset: offset,
       include: eagerIncludes                 
    }).then(function (results) {
        callback(results, options, undefined);
    }).catch(function (error) {
        callback(undefined, options, error);
    });

This results in:

ER_BAD_FIELD_ERROR: Unknown column 'playlist_entries.playlistId' in 'field list'

Any suggestions would be appreciated. Changing the column names in the database is not an option.

Note, this is an issue when trying to use the ' eager includes '.

根据一些实验,解决方法是将'foreignKey'属性添加到hasMany定义中:

entities.Playlist.hasMany(entities.PlaylistEntry, { foreignKey: 'playlist' });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM