2016-10-27 97 views
0

嵌套關係我有這些表:Laravel 5條件

用戶

| ID | ROLE_ID | clan_id |

角色

| id | slug |

氏族

| id |

我需要抓住所有用戶,其中蛞蝓是例如「領袖」

我該怎麼辦呢?

我走到這一步:

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; 
    } 
} 

但是,這並不算是智能。取而代之的是,我想將它加入了我的氏族表

戰隊:

| ID | leader_user_id |

所以我可以輕鬆訪問它。

非常感謝:)

回答

1

您可以創建戰隊和用戶的之間的關係one-to-many

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

而在你leader()功能,可以作爲寫:

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

    return $leader; 
} 

更新

要評論的下面

響應您可以創建範圍爲:

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

,您可以獲取Clan爲:

Clan::where('name', $clanname)->leader()->get() 
+0

但我不能做某事,如:家族: :where('name',$ clanname) - > leader(); – WLFCRK

+0

你想獲取用戶或家族? –

+0

我想取得部落,但是有一個參考領導者 - 用戶,所以我也可以訪問領導者用戶。那可能嗎? – WLFCRK