通过访问器更改hasManyThrough()关系属性名称

时间:2019-12-26 14:25:45

标签: laravel eloquent orm has-many-through

我有3个型号

  • 广告系列PK(id)
  • CampaignMedium FK(campaign_id)
  • 应收帐款FK(campaign_medium_id)(具有金额列)

控制器功能:

public function all()
{
    return Campaign::with(['customer', 'receivedPayments'])->get();
}

在Campaign模型中,关系定义如下:

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": []
    }
]
}

摘要:试图获取AccountReceivable金额属性的总和,效果很好,但 getReceivedPaymentsAttribute()不起作用,它仅需要返回总值。还可以有人帮助我解释为什么laravel_through_key和received_pa​​yments一起添加吗?

1 个答案:

答案 0 :(得分:0)

我从来没有尝试过使用属性修饰符来修改这种关系。您正在覆盖receivedPayments()的预期结果。最好像这样定义一个单独的属性:

public function getSumReceivedPaymentsAttribute()
{
    // ...your code... 
}

现在您可以使用$model->sum_received_payments访问该属性,也可以始终使用以下方式预加载该属性:

// model.php
protected $appends = ['sum_received_payments'];