我創造了許多像這樣用戶和角色之間的多對多關係:雄辯:查詢多對多的關係
用戶模型:
<?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
感謝@GauravRai,我需要選擇用戶編號和名稱並非所有的領域,是有辦法做到這一點? – YouneL
已更新的答案,一起看看 –
如何檢查未在您的答案中? @Gaurav Rai – Fawel