2017-08-24 201 views
0

我創造了許多像這樣用戶和角色之間的多對多關係:雄辯:查詢多對多的關係

用戶模型:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class User extends Model 
{ 
    /** 
    * The roles that belong to the user. 
    */ 
    public function roles() 
    { 
     return $this->belongsToMany('App\Role'); 
    } 
} 

榜樣:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Role extends Model 
{ 
    /** 
    * The users that belong to the role. 
    */ 
    public function users() 
    { 
     return $this->belongsToMany('App\User'); 
    } 
} 

我的問題是我如何才能獲得屬於某個特定角色名稱的用戶,例如,如果我有一個名爲「author」的角色名稱,我想獲得所有作者用戶,如下所示:sql:

SELECT users.id, users.name 
FROM users, roles, role_user 
WHERE users.id = role_user.user_id 
AND role_user.role_id = roles.id 
AND roles.name="author"; 

注:我使用Laravel 5.4

回答

1

您應該試試這個:

Role::with(array('user'=>function($query){ 
     $query->select('id','name'); 
    })) 
    ->where('role_name', 'author') 
    ->get(); 

希望爲你工作!!!

0
User::whereHas('roles', function($query){ 
    $query->where('role_name', 'author') 
}) 
->get(['name', 'id']); 

您可以爲表role更改列名,我已經使用role_name

現在,這應該工作,它會檢索名稱和ID僅適用於至少有一個角色的用戶

+0

感謝@GauravRai,我需要選擇用戶編號和名稱並非所有的領域,是有辦法做到這一點? – YouneL

+0

已更新的答案,一起看看 –

+0

如何檢查未在您的答案中? @Gaurav Rai – Fawel

0

你可以試試這個下面的代碼:

$userRoles = Role::where('name', 'author')->with('users')->get(); 
$userRoles->users->id; 
$userRoles->users->name; 

$userRoles = Role::select('users.id, users.name')->where('name', 'author')->with('users')->get();