Laravel 通过访问器更改hasManyThrough()关系属性名称
我有三种型号Laravel 通过访问器更改hasManyThrough()关系属性名称,laravel,eloquent,orm,has-many-through,Laravel,Eloquent,Orm,Has Many Through,我有三种型号 活动主键(id) 活动媒体FK(活动id) 应收账款FK(活动\媒体\ id)(有金额栏) 控制器功能: public function all() { return Campaign::with(['customer', 'receivedPayments'])->get(); } 活动模型中的关系定义如下: public function customer() { return $this->belongsTo(Customer::class
- 活动主键(id)
- 活动媒体FK(活动id)
- 应收账款FK(活动\媒体\ id)(有金额栏)
public function all()
{
return Campaign::with(['customer', 'receivedPayments'])->get();
}
活动模型中的关系定义如下:
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function accountReceivable()
{
return $this->hasManyThrough(AccountReceivable::class, CampaignMedium::class);
}
public function receivedPayments()
{
return $this->accountReceivable()
->selectRaw('sum(account_receivables.amount) as total')
->groupBy('campaign_id');
}
public function getReceivedPaymentsAttribute()
{
if (!array_key_exists('receivedPayments', $this->relations)) {
$this->load('receivedPayments');
}
$relation = $this->getRelation('receivedPayments')->first();
return ($relation) ? $relation->total : 0;
}
最终输出:
{
"data": [
{
"id": 8,
"name": "example",
"image": "campaign/90375849f6c3cc6b0e542a0e3e6295b890375849f6c3cc6b0e542a0e3e6295b8.jpeg",
"amount": 10,
"description": "saddsa",
"start_at": "2019-02-12 00:00:00",
"end_at": "2019-02-12 00:00:00",
"due_at": "2019-02-12 00:00:00",
"status": "active",
"customer": {
"id": 1,
"name": "test",
"email": "info@test.com",
"image": "customer/ec812116705ff3ae85298234fe6c4e97ec812116705ff3ae85298234fe6c4e97.jpeg",
"address": "sample address"
},
"received_payments": [
{
"total": "700",
"laravel_through_key": 8
}
]
},
{
"id": 9,
"name": "example",
"image": "campaign/fff9fadc92a809513dc28134379851aafff9fadc92a809513dc28134379851aa.jpeg",
"amount": 10,
"description": "saddsa",
"start_at": "2019-02-12 00:00:00",
"end_at": "2019-02-12 00:00:00",
"due_at": "2019-02-12 00:00:00",
"status": "active",
"customer": {
"id": 1,
"name": "test",
"email": "info@test.com",
"image": "customer/ec812116705ff3ae85298234fe6c4e97ec812116705ff3ae85298234fe6c4e97.jpeg",
"address": "sample address"
},
"received_payments": []
}
]
}
小结:尝试获取“应收账款金额之和”属性,该属性工作正常,但getReceivedPaymentsAttribute()不工作,只需要返回总值。还有谁能帮我解释一下为什么在收到的付款中添加laravel-through-key?我从来没有尝试过使用属性修饰符以这种方式修改关系。您正在覆盖
receivedPayments()
的预期结果。您最好定义一个单独的属性,如下所示:
公共函数getSumReceivedPaymentsAttribute()
{
//…你的代码。。。
}
现在,您可以使用$model->sum\u received\u payments
访问该属性,或者始终使用以下方法预加载该属性:
//model.php
受保护的$appends=[“收到的金额”];
它引发了一个异常:调用Strings上的成员函数AddagerConstraints(),它在哪里引发了该异常,在哪个函数上引发了该异常?在getSumReceivedPaymentsAttribute()函数上,您的属性函数正在生成以下查询:选择sum(应收账款
金额
)作为来自应收账款内部联接活动媒体上的活动媒体的聚合id
=应收账款活动媒体id
分组依据活动媒体id
,其中上一个关系正在生成:选择总和(应收账款.amount)作为总计,活动媒体
活动媒体
作为应收帐款
通过
的
应收帐款
内部连接活动媒体
关于活动媒体
id
应收账款
活动媒体
其中活动媒体
活动媒体
在(6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22)组中,通过campaign\u id