Skip to content
Advertisement

Sequelize – Include based on specific attribute

I have a model defined as follows:

sequelize.define('game', {
    id: {
        type: type.INTEGER,
        primaryKey: true,
        autoIncrement: true,
    },
    leaderId: {
        type: type.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'id',
        },
    },
    playerId: {
        type: type.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'id',
        },
    },
    status: {
        type: type.STRING,
        defaultValue: 'running',
    },
    notes: {
        type: type.TEXT,
    },
});

I’m trying to use Sequelize to load all game object and include the User with the id equal to the playerId field.

The problem is I have two attributes (leaderId, playerId) which reference the User model so using include as follows does not work:

Game.findAll({
    where: conditions,
    include: [{ model: User }],
})

Is there a way to specify which attribute the include command should use?

Advertisement

Answer

const game = sequelize.define('game', {
    id: {
        type: type.INTEGER,
        primaryKey: true,
        autoIncrement: true,
    },
    leaderId: {
        type: type.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'id',
        },
    },
    playerId: {
        type: type.INTEGER,
        allowNull: false,
        references: {
            model: 'users',
            key: 'id',
        },
        as:'player'
    },
    status: {
        type: type.STRING,
        defaultValue: 'running',
    },
    notes: {
        type: type.TEXT,
    },
});

game.associate = function (models) {
   game.belongsTo(models.user, {
      foreignKey: "playerId",
      as: "player",
   });

   game.belongsTo(models.user, {
      foreignKey: "leaderId",
      as: "leader",
   });
};

Game.findAll({
    where: conditions,
    include: ['player'],
})

Or

Game.findAll({
    where: conditions,
    include: [{model: User, as: 'player' }],
})

Or

Game.findAll({
    where: conditions,
    include: [{model: User, as: 'player', foreignKey: 'playerId' }],
})

https://github.com/nkhs/node-sequelize

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement