按 belongsToMany 关系字段过滤

Filter by belongsToMany relation field

无法使用链接 table 过滤数据。有两个 tables Instructor 和 Club。他们将 belongsToMany 联系起来。我需要获得 club_id = 值的所有讲师。

教师模型:

sequelize.define('Instructor', {
    instance_id: DataTypes.INTEGER,
    name: DataTypes.STRING(255)
}, {
    tableName: 'instructors',
    timestamps: false,
    classMethods: {
        associate: function (models) {
            Instructor.belongsToMany(models.Club, {
                through: 'InstructorClub'
            });
        }
    }
});

俱乐部型号:

sequelize.define('Club', {
    instance_id: DataTypes.INTEGER,
    name: DataTypes.STRING
}, {
    tableName: 'clubs',
    timestamps: false,
    classMethods: {
        associate: function (models) {
            Club.belongsToMany(models.Instructor, {
                through: 'InstructorClub'
            });
        }
    }
});

相关table:

sequelize.define('InstructorClub', {
    InstructorId: {
        type: DataTypes.INTEGER,
        field: 'instructor_id'
    },
    ClubId: {
        type: DataTypes.INTEGER,
        field: 'club_id'
    }
}, {
    tableName: 'instructors_clubs'
    timestamps: false
});

我正在尝试获取如下数据::

models
.Instructor
.findAll({
    include: [
        {
            model: models.Club,
            as: 'Clubs',
            through: {
                attributes: []
            }
        }
    ],
    # I need to filter by club.id
    where: {
        'Clubs.id': 10
    }
})

当前生成的查询 SQL:

SELECT  `Instructor`.`id`, 
    `Instructor`.`instance_id`, 
    `Instructor`.`name`, 
    `Clubs`.`id` AS `Clubs.id`, 
    `Clubs`.`name` AS `Clubs.name`, 
    `Clubs.InstructorClub`.`club_id` AS `Clubs.InstructorClub.ClubId`, 
    `Clubs.InstructorClub`.`instructor_id` AS `Clubs.InstructorClub.InstructorId` 
FROM `instructors` AS `Instructor` 
LEFT OUTER JOIN (`instructors_clubs` AS `Clubs.InstructorClub` INNER JOIN `clubs` AS `Clubs` ON `Clubs`.`id` = `Clubs.InstructorClub`.`club_id`) 
ON `Instructor`.`id` = `Clubs.InstructorClub`.`instructor_id` 
WHERE `Instructor`.`Clubs.id` = 10;

好吧,我需要这样的东西:

SELECT  `Instructor`.`id`, 
    `Instructor`.`instance_id`, 
    `Instructor`.`name`, 
    `Clubs`.`id` AS `Clubs.id`, 
    `Clubs`.`name` AS `Clubs.name`, 
    `Clubs.InstructorClub`.`club_id` AS `Clubs.InstructorClub.ClubId`, 
    `Clubs.InstructorClub`.`instructor_id` AS `Clubs.InstructorClub.InstructorId` 
FROM `instructors` AS `Instructor` 
LEFT OUTER JOIN (`instructors_clubs` AS `Clubs.InstructorClub` INNER JOIN `clubs` AS `Clubs` ON `Clubs`.`id` = `Clubs.InstructorClub`.`club_id`) 
ON `Instructor`.`id` = `Clubs.InstructorClub`.`instructor_id` 
# It should be like this:
WHERE `Clubs`.`id` = 10;

将您的 'where' 上移到包含(使用模型、as 和 through)。

include: [ { 
      model: models.Club, 
      as: 'Clubs', 
      through: { attributes: [] },
      where: { 'Clubs.id': 10 }
} ]