按belongsToMany关系字段过滤

时间:2015-05-20 01:27:16

标签: sql node.js orm sequelize.js

使用链接表过滤数据是不可能的。教练和俱乐部有两个表。他们与belongsToMany有关。我需要得到所有的俱乐部,其中club_id = value。

讲师模型:

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

相关表格:

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;

1 个答案:

答案 0 :(得分:1)

移动你的'在哪里'进入包含(使用模型,作为和通过)。

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