如何访问数据透视表列

时间:2016-11-25 17:02:26

标签: mysql laravel laravel-5 eloquent laravel-5.2

我有bican角色插件,我需要通过数据透视表访问。这是我的控制器代码

   $users = User::where('role_id','=',2)->get();

迁移角色

   Schema::create('roles', function (Blueprint $table) {
        $table->increments('id')->unsigned();
        $table->string('name');
        $table->string('slug')->unique();
        $table->string('description')->nullable();
        $table->integer('level')->default(1);
        $table->timestamps();
    });

迁移用户

   Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name')->unique();
        $table->string('email')->unique();
        $table->rememberToken();
        $table->timestamps();
    });

枢轴迁移

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

1 个答案:

答案 0 :(得分:1)

如果您的用户和角色之间的关系是多对多关系,那么您看起来错误地查询User。正确的查询将如下:

$users = User::whereHas('roles', function($q) {
                    $q->where('role_id', 2);
              })
              ->get();

然后你可以获得用户的角色:

foreach($users as $user) {
    $user->roles; // returns collection of roles
}