Get all records of relationship when parent doesn't exist

試著忘記壹切 提交于 2021-01-28 07:13:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!