Sequelize - 使用 where 和 limit 查询多对多关系

Sequelize - Query with Many-to-Many relationship using where and limit

我有这样的关系:

Clients -> ProgramsClients <- Programs

我想做的基本上是:

SELECT * FROM Programs p JOIN ProgramsClients pc on p.id = pc.programId WHERE pc.clientId = 1 LIMIT 0, 100;

我已经通过以下代码成功实现了这样的目标:

query = {
   include: [{
       model: models.Clients,
       attributes: [],
       require: true, 
   }],
   where: { '$Clients.id$': 1 }
}

models.Programs.findAll(query) // This works

生成:

SELECT [...]
FROM `programs` AS `Programs` LEFT OUTER JOIN ( 
`ProgramsClients` AS `Clients->ProgramsClients` 
INNER JOIN `clients` AS `Clients` 
ON `Clients`.`id` = `Clients->ProgramsClients`.`ClientId`) 
ON `Programs`.`id` = `Clients->ProgramsClients`.`ProgramId` 
WHERE `Clients`.`id` = 1;

这有效,但是当我尝试限制它时,出现错误。 代码:

query = {
   include: [{
       model: models.Clients,
       attributes: [],
       require: true, 
   }],
   limit: 0,
   offset: 10,
   where: { '$Clients.id$': 1 }
}

models.Programs.findAll(query) // This fails

生成:

SELECT [...]
FROM (SELECT `Programs`.`id`, `Programs`.`name`, `Programs`.`description`, `Programs`.`createdAt`, `Programs`.`updatedAt` 
FROM `programs` AS `Programs` WHERE `Clients`.`id` = 1 LIMIT 0, 10) AS `Programs` 
LEFT OUTER JOIN ( `ProgramsClients` AS `Clients->ProgramsClients` 
INNER JOIN `clients` AS `Clients` 
ON `Clients`.`id` = `Clients->ProgramsClients`.`ClientId`) 
ON `Programs`.`id` = `Clients->ProgramsClients`.`ProgramId`;

错误: DatabaseError [SequelizeDatabaseError]: Unknown column 'Clients.id' in 'where clause'

注意:我正在使用 MySQL 数据库。

有没有更简单的方法来解决这个问题并为 SQL 生成所需的(或类似的)结果?

提前致谢

我停了一下。当我回来时,我设法解决了它。

基本上,我误读了文档中的 super many-to-many section

您可以简单地定义 One-to-many 关系(即使您正在使用 many-to-many 关系)与关联的 table(在本例中为 ProgramsClients),然后包括 ProgramsClients 和做你想做的。 (您必须为此声明 ProgramsClients 的 id 列)。

query = {
   include: [{
       model: models.ProgramsClients,
       as: 'programsclient'
       attributes: [],
       require: true, 
       where: { clientId: 1 }
   }],
   limit: 0,
   offset: 10,
}