【问题标题】:Getting all data and only filtered relations获取所有数据和仅过滤的关系
【发布时间】:2021-09-29 11:57:26
【问题描述】:

我有一个与定价表相关的产品表,理想情况下,我希望获得所有产品的数组,并且那些与用户有定价关系的产品与产品相关联。

 return this.repo
        .createQueryBuilder("product")
        .leftJoinAndSelect("product.pricings", "pricings")
        .leftJoinAndSelect("pricings.driver", "driver")
        .where("pricings.driver.id = :id", { id: 1 })
        .getMany()

这将返回具有上述关系的产品数组,我想要所有产品,即使是那些与定价没有关系的产品。

【问题讨论】:

    标签: mysql sql backend nestjs typeorm


    【解决方案1】:
             SELECT  product.id, product.price,
                product.name, pricing.driverId, pricing.alteredPrice
                FROM    product   
                LEFT JOIN pricing 
                    ON product.id = pricing.productId AND
                        pricing.driverId = '1'
                ORDER   BY product.id
    

    这显然可以解决问题

    对于 typeorm,等价于:

              this.repo
                    .createQueryBuilder('product')
                    .leftJoinAndSelect("product.pricings", "pricing", "pricing.driverId = :driverId", { driverId })
                    .select('product.id')
                    .addSelect('product.price')
                    .addSelect('product.name')
                    .addSelect('product.saleType')
                    .addSelect('pricing.driverId')
                    .addSelect('pricing.alteredPrice')
                    .addSelect('pricing.id')
                    .orderBy("product.id")
                    .getMany()
    

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2022-09-27
      • 1970-01-01
      相关资源
      最近更新 更多