drtpbx3606 2016-10-27 08:44
浏览 72
已采纳

Laravel 5与条件的嵌套关系

I've these tables:

Users

|id|role_id|clan_id|

Roles

|id|slug|

Clans

|id|

I need to grab all Users where slug is for example 'leader'

How can I do it?

What I got so far:

class clan extends Model{
    public function leader() 
    {
        $leader = User::whereHas('role', function($query) {
            $query->where('slug', 'leader');
        })->where('clan_id', $this->id)->get();

        return $leader;
    }
}

But this wouldn't be smart. Instead of this I would like to have it joined my clans table

Clans:

|id|leader_user_id|

so I can access it easily.

Thanks alot :)

  • 写回答

1条回答 默认 最新

  • dourao3960 2016-10-27 09:00
    关注

    You can create a one-to-many relations between clan and user as:

    public function users()
    {
        return $this->hasMany('App\User');
    }
    

    And in your leader() function you can write as:

    public function leader() 
    {
        $leader = $this->users()->whereHas('role', function($query) {
            $query->where('slug', 'leader');
        })->get();
    
        return $leader;
    }
    

    Update

    To the response of comment below

    You can create a scope as:

    public function scopeLeader($query)
    {
        return $query->with(['users' => function($query) {
                   $query->whereHas('role', function($q) {
                        $q->where('slug', 'leader');
                    });
    }
    

    And You can fetch Clan as:

    Clan::where('name', $clanname)->leader()->get()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部