我有一个export_invoices
表,其中包含发票。
+----+----------------+
| id | title |
+----+----------------+
| 1 | First Invoice |
+----+----------------+
| 2 | Second Invoice |
+----+----------------+
和sold_products
与export_invoices
有关系。
+----+-------------------+------------+
| id | export_invoice_id | product_id |
+----+-------------------+------------+
| 1 | 1 | 1 |
+----+-------------------+------------+
| 2 | 1 | 1 |
+----+-------------------+------------+
| 3 | 1 | 2 |
+----+-------------------+------------+
| 4 | 2 | 1 |
+----+-------------------+------------+
| 5 | 2 | 1 |
+----+-------------------+------------+
我希望得到的东西:
我希望得到product_id = 1 is repeated 2 times
和product_id = 2 is repeated 1 time
这表示在发票中重复产品的频率。
答案 0 :(得分:0)
最简单的方法是从产品方面着手,假设您在产品和发票之间建立了关系
$products = App\Product::withCount('export_invoices')->get();
这将返回所有产品的集合,每个产品将具有一个名为export_invoices_count
的属性,该属性指出该产品出现在多少出口发票上。然后,您可以按export_invoices_count
对该集合进行排序,并获取前10个。
$top_ten = $products->sortByDesc('export_invoices_count')->take(10);