gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:21:09 24 4
gpt4 key购买 nike

我有这样的关系: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
您可以简单地定义与关联表(在本例中为 ProgramsClients)的一对多关系(即使您使用的是多对多关系),然后包含 ProgramsClients 并执行您想要的任何操作。 (您必须为此声明 ProgramsClients 的 id 列)。

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

关于javascript - Sequelize - 使用 where 和 limit 查询多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63929662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com