【问题标题】:Issue with group by laravel and sql通过 laravel 和 sql 分组的问题
【发布时间】:2019-05-16 15:56:58
【问题描述】:

首先,我遇到了计算每天销售的产品的问题。在sql中我有查询

select product_name, sum(quantity) as quantity from invoice_product 
join invoices on invoices.id = invoice_product.invoice_id
join products on products.id = invoice_product.product_id
 where invoices.issued_at = '2019-05-16' 
 and products.`made_by_us` = 1
 group by product_name

它向我展示了有趣的信息,但我使用 product_name 来制作 group by 但我应该使用 product_id - 我也需要显示名称,但我不知道该怎么做。

其次,我想在 Laravel 中使用它,所以也许有人知道在 Eloquent 中可以使用它吗?

提前谢谢你:)

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

    我会选择withCount()select(DB::raw()),像这样:

    $products = Product::withCount(['invoices as quantity' => function ($query) {
        $query->select(DB::raw('sum(quantity)'));
    }])->get();
    

    然后,您可以像这样访问每个数量总和:

    $quantity = $products->first()->quantity;
    

    【讨论】:

      【解决方案2】:

      您需要更新模型关系才能实现这一目标。

      型号:

      InvoiceProduct模特

      class InvoiceProduct extends Model
      {
          protected $table = 'invoice_product';
      
          protected $guarded = [
              'id',
          ];
      }
      
      public function invoice()
      {
          return $this->belongsTo('App\Invoice'); // Assuming `Invoice` Model is directly in app folder
      }
      
      public function product()
      {
          return $this->belongsTo('App\Product'); // Assuming `Product` Model is directly in app folder
      }
      

      控制器:

      $full_query = InvoiceProduct::whereHas('invoice', function ($query) {
         return $query->where('issued_at', '2019-05-16');
      })->whereHas('product', function ($query) {
         return $query->where('made_by_us', 1);
      });
      
      $product_names = $full_query->get(['product_name']);
      $total_quantities = $full_query->sum('quantity');
      

      【讨论】:

      • 谢谢你,它工作得很好,但我需要一种不同的方式,我需要product_namequantity 这个产品不是所有产品,如果你有我尝试自己做有时间请给我指路。最好的解决方案可能是$product_names = $full_query->get(['product_name'], sum['quantity']);,但它不起作用。
      • 我认为您需要按产品 ID 分组
      • 试试$product_names = $full_query->select('product_name', \DB::raw('SUM(quantity) as quantity'))->get()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      • 2012-02-19
      相关资源
      最近更新 更多