问题
I have two models.
Resource:
public function account()
{
return $this->belongsTo('App\Account');
}
Account:
public function resources()
{
return $this->hasMany('App\Resource');
}
I want to receive all resources of an account knowing user_id
from account Model.
Account::where('user_id', Auth::id())->first()->resources()->get();
This works only when account exists. It throws error otherwise: Call to a member function resources() on null
.
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.
回答1:
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();
Doc: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence
来源:https://stackoverflow.com/questions/65219020/get-all-records-of-relationship-when-parent-doesnt-exist