gpt4 book ai didi

subquery - Sequelize 使用急切加载的模型创建子查询的顶级

转载 作者:行者123 更新时间:2023-12-03 22:17:49 26 4
gpt4 key购买 nike

我遇到了一个问题,Sequelize 创建主模型的子查询,然后将包含与该子查询连接起来,而不是直接与主模型表连接。包含的查询条件最终位于子查询的 WHERE 子句中,这使其无效。我已经缩短了名称,希望在不丢失任何相关信息的情况下保持这种紧凑。

环境:
节点:6.11.3
Sequelize :3.23.6 => 更新到 4.38.1 并且问题仍然存在
MySql:5.7.23

代码截图模型:

I.model:
models.I.hasMany(models.II);
models.I.belongsTo(models.CJ);
models.I.belongsTo(models.CJS);
II.model:
models.II.belongsTo(models.I);
CJ.model:
models.CJ.hasMany(models.I);
models.CJ.hasMany(models.CJS);
CJS.model:
models.CJS.hasMany(models.I);

代码片段查询定义:
let where = { cId: '2',
iAmt: { '$gt': 0 },
'$or':
[ { '$CJ.a1$': {$like: '%246%'}} },
{ '$CJ.a2$': {$like: '%246%'} },
{ '$I.cPN$': {$like: '%246%'} }
] };

let query = {
where: where,
order: orderBy,
distinct: true,
offset: offset,
limit: limit,
include: [
{
model: CJ,
as: 'CJ',
required: false
}, {
model: CJS,
as: 'CJS',
required: false
}, {
model: II,
as: 'IIs',
required: false
}
]
};

I.findAll(query)

生成如下 SQL:
SELECT `I`.*, `CJ`.`_id` AS `CJ._id`, `CJS`.`_id` AS `CJS._id`, `IIs`.`_id` AS `IIs._id`
FROM (SELECT `I`.`_id`, `I`.`CJId`, `I`.`CJSId`, `I`.`CId`
FROM `Is` AS `I`
WHERE `I`.`CId` = '2' AND
`I`.`iA` > 0 AND
(`CJ`.`a1` LIKE '%246%' OR
`CJ`.`a2` LIKE '%246%' OR
`I`.`cPN` LIKE '%246%'
)
ORDER BY `I`.`iNum` DESC LIMIT 0, 10) AS `I`
LEFT OUTER JOIN `CJs` AS `CJ` ON `I`.`CJId` = `CJ`.`_id`
LEFT OUTER JOIN `CJSs` AS `CJS` ON `I`.`CJSId` = `CJS`.`_id`
LEFT OUTER JOIN `IIs` AS `IIs` ON `I`.`_id` = `IIs`.`IId`
ORDER BY `I`.`iNum` DESC;

我期待这样的事情:
SELECT `I`.*, `CJ`.`_id` AS `CJ._id`, `CJS`.`_id` AS `CJS._id`, `IIs`.`_id` AS `IIs._id`
FROM `Is` AS `I`
LEFT OUTER JOIN `CJs` AS `CJ` ON `I`.`CJId` = `CJ`.`_id`
LEFT OUTER JOIN `CJSs` AS `CJS` ON `I`.`CJSId` = `CJS`.`_id`
LEFT OUTER JOIN `IIs` AS `IIs` ON `I`.`_id` = `IIs`.`IId`

WHERE `I`.`CId` = '2' AND
`I`.`iA` > 0 AND
(`CJ`.`a1` LIKE '%246%' OR
`CJ`.`a2` LIKE '%246%' OR
`I`.`cPN` LIKE '%246%'
)
ORDER BY `I`.`iNum` DESC LIMIT 0, 10

如果我从包含中删除 II 模型,它确实可以工作并将 WHERE 移动到顶层。我承认这里的查询结构并不简单, I CJ CJS 的子级,而 CJS 又是 CJ 的子级。然后是 II I 的 child 。我在这里缺少什么?

Bueller 或任何人的 2 美分欢迎!

最佳答案

这里发生的事情是因为您还将 orderlimit 与预先加载关联 see the issue 一起使用

为了使它工作,有一个小技巧,您需要将 subQuery: false 一起添加到您的根模型查询中

let query = {
where: where,
order: orderBy,
distinct: true,
offset: offset,
limit: limit,
subQuery: false,
include: [...]
};

关于subquery - Sequelize 使用急切加载的模型创建子查询的顶级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52303647/

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