Laravel:将2个查询合并为1个

问题描述

我有以下关系:

“订单”-> manyToMany->“产品”

'订单'-> manyToMany->'collis'-> manyToMany产品

Image of entity relation diagram

不要介意图片中的其他表格。

我想检索所有已订购的产品,并获取每种产品的总量。结果应类似于:

[{id: 6,name: "steak",category_name: "beef",total_product_quantity: "2.00"}
{id: 7,name: "bacon",category_name: "pork",total_product_quantity: "1.00"}
{id: 9,name: "chicken filet",category_name: "chicken",total_product_quantity: "1.00"}

我得到的所有产品都没有考虑到colli's

$allProducts = DB::query()
      ->select(['p.id','p.name','c.name as category_name',DB::raw('sum(op.quantity) as total_product_quantity')])
      ->from('products as p')
      ->join('order_product as op','p.id','=','op.product_id')
      ->join('orders as o','op.order_id','o.id')
      ->join('categories as c','p.category_id','c.id')
      ->groupBy('p.id');

以及colli的所有产品

$allProductsInAllCollis = DB::query()
      ->select(['p.id',DB::raw('sum(co.quantity * colp.quantity) as total_product_quantity')])
      ->from('products as p')
      ->join('colli_product as colp','colp.product_id')
      ->join('collis as col','colp.colli_id','col.id')
      ->join('colli_order as co','col.id','co.colli_id')
      ->join('orders as o','co.order_id','col.category_id','c.id')
      ->groupBy('p.id','category_name');

两个查询都返回与上述相同的表结构(数组)。但是现在我想将第一个表的total_product_quantity添加到第二个表,并返回合并的表。我该怎么办?

我对sql甚至laravel查询生成器的了解都很少,因此,如果有更好的方式编写查询(也许更雄辩?),请告诉我!

解决方法

您可以使用关系来获取数据, 这种关系是hasManyThrough

尝试:

按型号顺序

public function products(){
        return $this->hasManyThrough(Colli::class,Product::class)->withPivot('quantity');

    }