Laravel Where Condition on Grand Parent Eloquent 关系

Laravel Where Condition on Grand Parent Eloquent Relation

我有 4 张桌子:

Account (id, name)

Type (id, account_id, name)

Category (id, type_id, name)

Money (id, category_id, date, amount)

我在模型中定义了关系

但我的问题是如何获取帐户 ID 为 2 的资金数据?

Account::find(2)-> type()-> category()->money

不工作

假设你建立了你的关系,你可以这样做:

$account = Account::with('type.category.money')->find(2);

现在可以使用:

来展示金钱
echo $account->type->category->money->amount;

在上面 echo 我当然假设对于每条记录,您在所有这些表中都有数据。如果不是,您需要添加额外的检查以确保您不会为 null

显示 属性

如果您只需要 'money' 的最终结果并在模型上设置反向关系,您也可以从另一个方向着手。

$money = Money::whereHas('category.type.account', function ($q) use ($id) {
    $q->where('id', $id);
})->get();

// get() or first() depending whether these relationships return many

Laravel Docs - Eloquent Relationships - Querying Relationships - Querying Relationship Existence