当父母不存在时获取所有关系记录 [英] Get all records of relationship when parent doesn't exist
问题描述
我有两个模型.
资源:
public function account()
{
return $this->belongsTo('App\Account');
}
帐户:
public function resources()
{
return $this->hasMany('App\Resource');
}
我想从帐户模型接收知道 user_id
的帐户的所有资源.
I want to receive all resources of an account knowing user_id
from account Model.
Account::where('user_id', Auth::id())->first()->resources()->get();
这仅在帐户存在时有效.否则会引发错误:对成员函数resources()的调用为空
.
This works only when account exists. It throws error otherwise: Call to a member function resources() on null
.
在Eloquent中获取所有资源的明智方法是什么?最好是在后台仅使用一个查询语句,因为我知道上面的示例正在使用两个查询.
What's the smart way to get all resources in Eloquent? The best would be to use only one query statement in the background, because I know above example is using two queries.
推荐答案
您可以利用 whereHas()
雄辩的方法来选择附加到帐户的所有
.试试这个:资源
属于特定 user_id
的
You can leverage the whereHas()
eloquent method to select all Resources
attached to account
who belongs to a specific user_id
. Try this:
$resources = Resource::whereHas('account', function ($query)
{
$query->where('user_id', Auth::id());
})->get();
文档: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
这篇关于当父母不存在时获取所有关系记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!