【问题标题】:Using joinRelated for multiple relation filtering使用 joinRelated 进行多重关系过滤
【发布时间】:2020-11-22 17:35:18
【问题描述】:

我有一个collection、一个product 和一个collection_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)

我能够获取所有具有属于某个集合的父级的子级产品,但不能获取父级产品。我怎样才能两者兼得?

【问题讨论】:

    标签: knex.js objection.js


    【解决方案1】:

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

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

    而不是.joinRelated。它还应该包括与结果的连接关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多