我有两张table, customers
以及 customer_invoices
,我想获得所有客户的发票上都有一个条件,并选择特定的列(customers.id、customers.last\u 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))"
如果不使用连接,如何实现这一点?
1条答案
按热度按时间xzv2uavs1#
你可以用
withCount()
从相关模型中求和另一种求和的方法,可以定义
hasOne()
客户模型中的关系在查询生成器中
根据eloquent:withcount()重写get()上的$columns
select()
方法然后使用with()
功能