代码之家  ›  专栏  ›  技术社区  ›  Alk

Sequelize-基于特定属性包含

  •  0
  • Alk  · 技术社区  · 4 年前

    我的模型定义如下:

    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,
        },
    });
    

    我正在尝试使用Sequelize加载所有 game User playerId 现场。

    问题是我有两个属性( leaderId 玩家ID )哪个参考 用户 include 以下情况不起作用:

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

    有没有办法指定 命令应该使用?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Wang Liang Sandeep Pathak    4 年前
    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' }],
    })