Laravel 处理不相关的关系

Laravel working with relations that arent related

假设我有三个模型:SubscriptionDescriptionExpense

每个订阅都属于一个描述,每个描述都有很多费用:

模型订阅:

public function description()
{
    return $this->belongsTo(Description::class);
}

型号说明:

public function expenses()
{
    return $this->hasMany(Expense::class);
}

模特费用:

public function description()
{
    return $this->belongsTo(Description::class);
}

我希望能够根据描述检索所有订阅费用。当我有一个订阅时,我可以这样做:

$subscription->load(['description.expenses' => function ($q) use (&$transactions, $subscription) {
    $transactions = $q->with('description')
        ->get());
}]);

但是当我想查看所有订阅的所有费用时,我不确定如何去做。我试过使用 hasManyThrough,但我认为这根本行不通,因为我的 DescriptionExpense 都有 subscription_id。我也不想为 SubscriptionExpense.

建立直接关系

关于如何获取所有订阅的所有费用的任何指示?或者更确切地说,所有订阅的所有费用总和?

您可以在 Subscription 模型上附加一个属性:

<?php
class Subscription extends Model {
    protected $appends = ['total_expenses'];

    ...

    public function totalExpenses()
    {
        return $this->description()
                    ->with(['expenses'])
                    ->get()
                    ->pluck('expenses.amount', 'amount')
                    ->sum('amount');
    }
}


// do something...
Subscription::all()->each->total_expenses

我实际上可以做与我已经发布的相同的事情:

Subscription::all()->load(['description.expenses' => function ($q) use (&$transactions) {
    $transactions = $q->get();
}]);