Sql 按隶属关系字段筛选
使用链接表过滤数据是不可能的。有两张桌子和俱乐部。他们讲述了归属感。我需要得到所有俱乐部id=价值的教练 讲师模式:Sql 按隶属关系字段筛选,sql,node.js,orm,sequelize.js,Sql,Node.js,Orm,Sequelize.js,使用链接表过滤数据是不可能的。有两张桌子和俱乐部。他们讲述了归属感。我需要得到所有俱乐部id=价值的教练 讲师模式: sequelize.define('Instructor', { instance_id: DataTypes.INTEGER, name: DataTypes.STRING(255) }, { tableName: 'instructors', timestamps: false, classMethods: { asso
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;
将您的“where”向上移动到包含中(使用模型、as和through)
您是否尝试将“where”向上移动到include中(使用model、as和through)。我以前试过,没用。非常感谢。@MarkLeiber加上这个作为答案,我会把它标记为正确的。
include: [ {
model: models.Club,
as: 'Clubs',
through: { attributes: [] },
where: { 'Clubs.id': 10 }
} ]