想要获取在Laravel相关表中具有公共行的最大记录

时间:2018-09-19 09:49:19

标签: laravel eloquent

我在laravel中有三个表,一个是中间表:

创建表订单(id INT(10)PRIMARY KEY NOT NULL AUTO_INCREMENT,order_number VARCHAR(100)NOT NULL);

创建表产品(id INT(10)主键NOT NULL AUTO_INCREMENT,标题VARCHAR(100)NOT NULL);

创建表orders_products(order_id INT(10)不为空,product_id INT(10)不为空);

我要检索具有共同产品的前两个订单,此处较高的数量无关紧要,

重要的是orderC具有5个订单,1、3、4、5、7和orderF也具有1,2、3、4、5、6、8,因此它们具有1,3、4、5总的来说,这就是我想要的,即使其他人拥有一个2,7,9,12,13,15,17,23和其他2,4,6,8,9,11,12,14,15 ,16,17并不是我想要的,但是这些产品拥有最多的共同点

非常感谢

结果不正确:

  $orders = 
  DB::table('orders')
 ->select('orders.id as ordid', 'orders.order_number as order_number',

     DB::raw('COUNT(orders_products.product_id) as counter'  )  )
    ->join('orders_products', 'orders.id', '=', 'orders_products.order_id')
    ->join('products as prod1', 'prod1.id', '=', 

     'orders_products.product_id')
    ->join('products as prod2', 'prod1.id', '=', 'prod2.id')
    ->groupBy(  'orders.order_number')
    ->orderByRaw('MAX(orders_products.product_id) DESC')

    ->limit(2)
    ->get();

1 个答案:

答案 0 :(得分:0)

要获得产品数量最多的订单,您需要使用HAVING子句和一个子查询才能获得所需的结果。

下面的查询是这样的:

  1. 首先,子查询(带有嵌套子查询)以单个订单查找最多数量的产品-highest_amount
  2. 然后,包装查询从子查询中查找所有订单,其中订单的商品数量最多的是

它看起来像这样:

SELECT 
   orders.id as ordid, 
   orders.order_number as order_number, 
   COUNT(orders_products.product_id) as counter
FROM orders
JOIN orders_products ON orders.id = orders_products.order_id
JOIN products ON products.id = orders_products.product_id
GROUP BY orders.order_number
HAVING COUNT(orders_products.product_id) >= (
   SELECT MAX(products_in_order) as highest_amount FROM (
      SELECT COUNT(orders_products.product_id) as products_in_order
      FROM orders
      JOIN orders_products ON orders.id = orders_products.order_id
      JOIN products ON products.id = orders_products.product_id
      GROUP BY orders.order_number
   ) top_amounts
)

我在此SQL fiddle中对其进行了测试-它可以按预期工作(您收到的所有产品订单最多-在这种情况下为3)