drtpbx3606 2016-10-27 16: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 17: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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?