Laravel:如何检索在此示例中具有特定角色的用户列表?

时间:2014-07-16 02:41:34

标签: laravel laravel-4

用户迁移:

/**
     * Users
     */
    Schema::create('users', function(Blueprint $t) {
        $t->increments('id');
        $t->string('email', 100)->unique();
        $t->string('password', 60);
        $t->string('firstname', 30);
        $t->string('lastname', 30);
        $t->string('company', 60)->nullable();
        $t->string('phone')->nullable();
        $t->rememberToken();
        $t->timestamps();
    });

角色迁移:

Schema::create('roles', function(Blueprint $t) {
        $t->increments('id');
        $t->string('name', 30)->unique();
    });

数据透视表:

Schema::create('role_user', function(Blueprint $t) {
            $t->increments('id');
            $t->integer('role_id')->unsigned()->index();
            $t->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');

            $t->integer('user_id')->unsigned()->index();
            $t->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });

关系工作正常,但我需要检索所有具有特定角色的用户的列表,让我们说" Agent"

最终我想将此用户列表添加到Form :: select中,因此我只需要users表中的 id,firstname,lastname 字段。

好的,在输入所有内容之后,我想出来了。想要提交,以防其他人觉得它有用,或者给我一个更好的方法。以下是:

我首先将此添加到用户模型:

public function getFullNameAttribute() {     返回$ this->属性[' firstname']。 ' ' 。 $这 - >属性['姓']; }

然后我收到准备控制器中的数据:

$agents = User::select('firstname', 'lastname', 'id')->with(['roles' => function($query) {
    $query->where('name', 'Agent');
}])->get();

$agentsList = $agents->lists('fullName', 'id');

这似乎有效,但我不确定它是否是一种处理它的正确方法。该页面很少被使用,因此性能不会太重要。

1 个答案:

答案 0 :(得分:2)

您可以试试这个,whereHas只会获取name=Agent但会获取所有内容的人:

$agents = User::whereHas('roles', function($query) {
    $query->where('name', 'Agent');
})->get(['firstname', 'lastname', 'id'])->lists('fullName', 'id');
相关问题