【问题标题】:Laravel most repeated product in each invoiceLaravel 每张发票中重复次数最多的产品
【发布时间】:2019-12-19 17:01:49
【问题描述】:

我有两张桌子export_invoicessold_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 出现的次数是发票中产品的重复次数。考虑到如果产品在一张发票中重复多次,这意味着它只需要一次

标签: mysql laravel


【解决方案1】:

您必须更改分组依据才能对产品 ID 进行分组,仅此而已。
来自

groupBy('sold_products.product_id', 'sold_products.export_invoice_id')

groupBy('sold_products.product_id')

【讨论】:

  • 这个返回次数总是等于1!我想要发票中最需要的产品
  • 我使用了你的答案,并从 groupBy('sold_products.product_id', 'sold_products.export_invoice_id') 更改为 groupBy('sold_products.product_id') 并且效果很好,达到了预期的效果。请更新你的答案,以便我接受。它可能对某人有所帮助。
猜你喜欢
  • 1970-01-01
  • 2018-01-18
  • 1970-01-01
  • 2019-12-25
  • 2021-09-15
  • 2019-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多