我有2个表,customers
和customer_invoices
,我想让所有客户的发票都有条件,然后选择特定的列(customers.id,customers.last_name和每个客户的发票total_price
的总和),我得到以下查询:
$result = Customer::whereHas('customerInvoices', function(Builder $q) {
$q->where('customer_invoices.status', 1);
})->select([
'customers.id',
'customers.last_name',
\DB::raw('SUM(customer_invoices.total_price) as sum')
])->get();
customerInvoices
是关系:
public function customerInvoices() {
return $this->hasMany(CustomerInvoice::class);
}
我想使用子查询而不是联接,所以在这里我不能选择此\DB::raw('SUM(customer_invoices.total_price) as sum')
,否则我当然会收到此错误:
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'customer_invoices.total_price' in 'field list' (SQL: select `customers`.`id`, `customers`.`last_name`, SUM(customer_invoices.total_price) as sum from `customers` where exists (select * from `customer_invoices` where `customers`.`id` = `customer_invoices`.`customer_id` and `customer_invoices`.`status` = 1))"
如何在不使用联接的情况下实现这一目标?
答案 0 :(得分:1)
您可以使用withCount()
从相关模型中获取总和,
@Valid
另一种求和的方法,您可以像在客户模型中定义$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();
关系
hasOne()
在查询生成器中
public function invoice_sum()
{
return $this->hasOne(CustomerInvoice::class)
->select('customer_id',
DB::raw('sum(total_price)')
)->groupBy('customer_id');
}
根据Eloquent : withCount() overrides the $columns on get()问题,首先放置$result = Customer::select([
'customers.id',
'customers.last_name',
])->with('invoice_sum')
->whereHas('customerInvoices', function(Builder $q) {
$q->where('customer_invoices.status', 1);
})->get();
方法,然后使用select()
函数