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 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启