Select SUM from subquery while using whereHas in Laravel

后端 未结 1 1724
闹比i
闹比i 2021-01-24 11:51

I have 2 tables, customers and customer_invoices, and I want to get all the customers with a condition on their invoices, and select specific columns (

相关标签:
1条回答
  • 2021-01-24 12:14

    You can use withCount() to get sum from related model as

    $result = Customer::select([
                'customers.id',
                'customers.last_name'
            ])->withCount([
                'customerInvoices as invoice_sum' => function($query) {
                    $query->select(DB::raw('SUM(total_price)'));
                }
            ])->whereHas('customerInvoices', function(Builder $q) {
                $q->where('customer_invoices.status', 1);
            })->get();
    

    Another approach to get sum, you can define a hasOne() relation in your Customer model like

    public function invoice_sum()
    {
        return $this->hasOne(CustomerInvoice::class)
            ->select('customer_id',
                DB::raw('sum(total_price)')
            )->groupBy('customer_id');
    }
    

    And in query builder

    $result = Customer::select([
                'customers.id',
                'customers.last_name',
            ])->with('invoice_sum')
              ->whereHas('customerInvoices', function(Builder $q) {
                $q->where('customer_invoices.status', 1);
            })->get();      
    

    As per Eloquent : withCount() overrides the $columns on get() issue first put select() mehtod and then use with() function

    0 讨论(0)
提交回复
热议问题