php - 从数据库(外键)恢复用户角色

标签 php mysql sql laravel laravel-5

谁能告诉我如何从我的数据库中恢复用户角色? 知道我有 3 个表(用户、角色、用户角色) 迁移:

表用户:

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

        });
    }

表角色:

public function up()
       {
        Schema::create('roles', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });
       }

表用户角色:

public function up()
         {
        Schema::create('user_role', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id');
            $table->integer('role_id');
            $table->timestamps();
        });
       }

我的 Controller 中返回用户列表的函数是 membrevis():

 public function membrevis()
     {
      $filter = isset($_GET['filter']) ? $_GET['filter'] : null;
        $query = DB::table('users')
        ->join('user_role', 'users.id', '=', 'user_role.user_id')
        ->join('roles', 'user_role.role_id', '=', 'roles.id')
        ->where('users.valid','=',1)
        ->select('users.*','roles.description');

    if ($filter != null) {
        $query->where('users.name','like','%'.$filter.'%')
            ->orWhere('roles.description','like','%'.$filter.'%');
         }

       $itemsPerPage = 8 ;
       $currentPage  = isset( $_GET['page'] ) && is_numeric( $_GET['page'] ) ? $_GET['page'] : 1;
         $urlPattern   = '/membre2?page=(:num)';
         $totalItems   = $query->count();
      $donner   = $query->offset( ( $currentPage - 1 ) * $itemsPerPage )->limit( $itemsPerPage )->get();
       $paginator = new  Paginator( $totalItems, $itemsPerPage, $currentPage, $urlPattern );

      return view('membre2',['users'=> $donner,'paginator'=> $paginator]);
     }

我可以在这里修改什么来恢复用户和他们的角色?外键问题

最佳答案

我建议您使用 Laravel 模型和关系。

这里有用户和角色之间的关系。这种关系在所谓的中间 表中定义,在本例中为user_roles 表。

用户和角色之间存在一种多对多类型的关系,其中一个用户可以拥有多个角色,并且一种角色类型可以分配给多个用户。

我建议您阅读以下内容:https://laravel.com/docs/5.2/eloquent-relationships#many-to-many

那是针对 Laravel 5.2 的,但你会看到每个 Laravel 5.x 版本的文档。您将在那里学习如何建立这些关系以及如何有效地使用它们。

关于php - 从数据库(外键)恢复用户角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50938544/

相关文章:

php - 如何在 PHP 查询中使用通配符

php - 无法从 App Engine 应用程序连接到 MySQL 第二代实例(灵活环境) PHP

mysql - Rails belongs_to 和 has_many 没有创建主外键关系

sql - 从数据库中获取架构(用户)名称

php - 如何使用php redis获取redis中的所有键?

javascript - 在 codeigniter 中链接 Javascript

c# - 如何编写 linq 语句来获取一组记录中的最后一条记录

MYSQL 计数跨表事件的位置

php - PHP 无状态 Web 应用程序中的持久多节点事件

MySQL CAST 函数不起作用并作为列名输出