我不是一位熟练的Eloquent大师,我做了很多研究但无法得到期望的结果。
我有以下模型:
<?php
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
protected $fillable = [
'uuid',
'number_id'
];
protected $dates = [
'started_at',
'ended_at'
];
public $timestamps = false;
public function contacts()
{
return $this->hasMany(Contact::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $fillable = [
'incoming_messages',
'outgoing_messages',
'outgoing_template_messages',
];
public $timestamps = false;
public function invoice()
{
return $this->belongsTo(Invoice::class);
}
}
当我搜索特定的 Invoice::class
时:
$invoice = Invoice::number($number)
->latest('started_at')
->with(['contacts'])
->firstOrFail();
我需要以这种方式返回:
{
"id": 1,
"number_id": "444a13fd-9789-426e-bdfb-c3e2e83c4422",
"incoming_messages": 10, #(sum of invoice.contacts.incoming_messages)
"outgoing_messages": 10, #(sum of invoice.contacts.outgoing_messages)
"outgoing_template_messages": 10, #(sum of invoice.contacts.outgoing_template_messages)
"started_at": "2020-07-01T00:00:00.000000Z",
"ended_at": "2020-07-31T23:59:59.000000Z"
}
我目前是在 InvoiceResource::class
类中执行此操作:
$incoming_messages = $this->contacts->sum('incoming_messages');
$outgoing_messages = $this->contacts->sum('outgoing_messages');
$outgoing_template_messages = $this->contacts->sum('outgoing_template_messages');
然而,数据量非常大,我想删除 EagerLoading
并在单个查询中完成所有操作,以减少对数据库的影响。
有什么想法可以只使用 Eloquent
来解决这个问题吗?
更新
朋友帮我编写了一个查询语句,我想将其转换为 Eloquent
:
SELECT a.number_id
, sum(incoming_messages) as 'incoming_messages'
, sum(outgoing_messages) as 'outgoing_messages'
, sum(outgoing_template_messages) as 'outgoing_template_messages'
, a.started_at
, a.ended_at
FROM invoices a
inner join contacts b on a.id = b.invoice_id
Where number_id = '45bh1h2g14h214hg2'
Group By a.started_at , a.ended_at
EagerLoading
,因为它目前可以节省很多查询。我认为你现在应该只有两个:一个获取发票,一个获取发票的联系人。执行$this->contacts->sum('incoming_messages');
不会产生额外的查询。 - thefallenEagerLoading
会将所有联系人数据返回给我,而最终我只需要指定列的总和。Mysql可以在不返回所有联系人的情况下进行求和,这将节省一些资源... - Caio KawasakiInvoice::hydrateRaw('<your_raw_query>', <bindings>)
。 - Paul Spiegel