使用joinRelated进行多重关系筛选



我有一个collectionproductcollection_product联接表。如果我试图根据集合ID过滤产品,我会执行以下操作:

Product.query()
.modify((builder) => {
if (collectionIds?.length) {   
builder 
.joinRelated({ collections: true })
.whereIn('collections.id', collectionIds)
.groupBy('product.id');  
}
}

现在,我们将子产品添加到product表中,它们与常规产品相同,只是它们在parent_product_id列中包含父id。

这些子产品不是collection_product表的一部分,因此上面的修饰符将只返回父产品。如果父产品匹配,是否有方法将子产品也包括在结果中?

我尝试同时加入collectionsparentProduct.collections,但没有成功。它们只能单独工作。因此,通过这样做:

.joinRelated({ parentProduct: { collections: true } })
.whereIn('parentProduct:collections.id', collectionIds)

我能够获得所有有属于一个集合的父母的儿童产品,但不能获得父母产品。我怎样才能两者都得到?

也许您应该使用.withGraphJoined({ parentProduct: { collections: true } })

https://vincit.github.io/objection.js/api/query-builder/eager-methods.html#withgraphjoined

而不是CCD_ 10。它还应包括与结果的连接关系。

最新更新