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

问题描述 投票:0回答:1

我有3个型号

  • 广告系列PK(id)
  • CampaignMedium FK(campaign_id)
  • AccountReceivableable FK(campaign_medium_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": "[email protected]",
            "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": "[email protected]",
            "image": "customer/ec812116705ff3ae85298234fe6c4e97ec812116705ff3ae85298234fe6c4e97.jpeg",
            "address": "sample address"
        },
        "received_payments": []
    }
]
}

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

laravel eloquent orm has-many-through
1个回答
0
投票
我从未尝试过使用属性修饰符以这种方式修改关系。您正在覆盖receivedPayments()的预期结果。您最好像这样定义一个单独的属性:
© www.soinside.com 2019 - 2024. All rights reserved.