doutizha7526 2014-03-18 09:57
浏览 57
已采纳

让所有用户在Laravel中扮演角色

I'm working in this Laravel project which has this structure

users: id | first_name |...

roles: id | name

assigned_roles: id | user_id | role_id

I think this is quite obvious :p

User model

class User extends ConfideUser {
use HasRole;

public function Roles(){
    return $this->belongsToMany('Role','assigned_roles');
}

Role model

class Role extends EntrustRole
{
public function Users()
{
    return $this->belongsToMany('User','assigned_roles');
}


} 

I'm looking for a way to get all users with a specified role in this case 'Teacher'. I've tried this:

$students = User::with(array('Roles' => function($query) {
        $query->where('name','Teacher');
    }))
    ->get();
    return $students;

but this always returns an array of all users.

would anyone know why that's so? Thanks!

展开全部

  • 写回答

1条回答 默认 最新

  • dqjgf0982 2014-03-18 13:41
    关注

    What you're currently asking laravel for in your $students query, is 'give me all the students, and for each student get me all of their roles if the role is teacher'

    Try using the whereHas

    $students = User::whereHas(
        'roles', function($q){
            $q->where('name', 'Teacher');
        }
    )->get();
    

    This should get you the users, but only where they have a role where the name is teacher.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部