问题描述
在 sequelize 中,我想在 sub-sub 子模型的 findAndCountAll 调用中添加一个条件。如果条件为假,它应该影响父模型, findAndCountAll 应该返回数组长度 0。目前,只有子子模型的数组长度为 0,其余父模型正在返回。
const { limit,offset } = dbHelpers.GetPagination(
req.query.limit,req.query.offset
);
const results = await models.ModelA.findAndCountAll({
where: condition,distinct: true,limit,offset,order: [["id","DESC"]],include: [
{
model: models.ModelB,as: "ModelB",include: [
{
model: models.ModelC,separate: true,},{
model: models.ModelD,include: [
{
model: models.ModelE,{
model: models.ModelF,where: "I want to add my condition here which should impact the whole query if not found just like the condition I have added in ModelG",],{
model: models.ModelG,where: "I have added a condition here and if nothing is found,my parent query returns nothing which is exactly what I want.",include: [
{
model: models.ModelH,as: "ModelH",});
解决方法
好的,所以我想出了解决方案,但添加了一个带有连接的原始查询,在其中我在需要的地方添加了所需的条件并获取了主模型的 ID。然后我使用 sequelize 在 where 子句中添加这些 id 来获取数据。我的代码现在看起来像这样。
const { limit,offset } = dbHelpers.GetPagination(
req.query.limit,req.query.offset
);
let querySting = "(SELECT count(DISTINCT p.id) FROM ModelA p " +
"JOIN ModelB cp ON cp.pId = p.id " +
"JOIN ModelC cs ON cs.cpId = cp.id " +
"JOIN ModelD ms ON ms.csId = cs.id " +
"LEFT JOIN ModelE sa ON sa.msId = ms.id " +
"LEFT JOIN ModelF pp ON pp.msId = ms.id " +
"LEFT JOIN ModelG sta ON sta.ppId = pp.id " +
"LEFT JOIN ModelH ol ON ol.cdId = cd.id " +
"WHERE " //you can add your conditions here
+ " ORDER BY p.id desc LIMIT " + offset + "," + limit + ")"
const rawQuery = await models.sequelize.query(querySting,{ type: QueryTypes.SELECT })
const Ids = rawQuery.map(result => result.id)
const results = await models.ModelA.findAndCountAll({
where: {
id: Ids
},include: [
{
model: models.ModelB,as: "ModelB",include: [
{
model: models.ModelC,separate: true,},{
model: models.ModelD,include: [
{
model: models.ModelE,{
model: models.ModelF,],{
model: models.ModelG,include: [
{
model: models.ModelH,as: "ModelH",});