【发布时间】:2019-12-19 17:01:49
【问题描述】:
我有两张桌子export_invoices 和sold_products。
这里的关系是一对多的(每张发票都有很多已售出的产品)。
我想做什么:
我正在尝试获取出口发票中重复(出现)次数最多的产品。
export_invoices表:
+----+-------+
| id | title |
+----+-------+
| 1 | 1 |
| 2 | 1 |
+----+-------+
sold_products表:
+----+-------------------+------------+------------+
| id | export_invoice_id | product_id | sold_price |
+----+-------------------+------------+------------+
| 1 | 1 | 205 | 12 |
| 2 | 1 | 205 | 15 |
| 3 | 2 | 205 | 12 |
| 4 | 2 | 301 | 20 |
| 5 | 2 | 302 | 30 |
+----+-------------------+------------+------------+
现在出现次数最多的产品报告应如下所示:
[
{
"product_id": "205",
"occurrences": "2"
},
{
"product_id": "301",
"occurrences": "1"
}
]
我尝试过的:
$columns = ['sold_products.deleted_at', 'export_invoices.deleted_at'];
$report_data = ExportInvoice::join('sold_products', 'sold_products.export_invoice_id', '=', 'export_invoices.id')
->join('products', 'sold_products.product_id', '=', 'products.id')
->select(
'sold_products.product_id',
DB::raw('
COUNT(DISTINCT(sold_products.export_invoice_id))
as occurrences
')
)
->whereYear('export_invoices.date', $year)
->where(function($q) use ($columns) {
foreach ($columns as $column) {
$q->whereNull($column);
}
})
->groupBy('sold_products.product_id', 'sold_products.export_invoice_id')
->orderBy('occurrences', 'DESC')
->limit(20)
->get();
return $report_data;
这个回报:
[
{
"product_id": "205",
"occurrences": "3" // WRONG NUMBER
},
{
"product_id": "301",
"occurrences": "1"
}
]
无法对产品进行分组
【问题讨论】:
-
export_invoices中的title字段没用吧?
-
int 你给的表是 205 产品的 3 倍,所以我相信出现的次数是将该产品作为已售产品之一的发票数量,对吧?我也可以看到这个查询不依赖于任何值,那你为什么不能写一个原始的 SQL 查询呢?
-
@AlbertoSinigaglia 是的,标题字段没用
-
@AlbertoSinigaglia 出现的次数是发票中产品的重复次数。考虑到如果产品在一张发票中重复多次,这意味着它只需要一次