我创造了许多像这样用户和角色之间的多对多关系:雄辩:查询多对多的关系
用户模型:
<?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