【问题标题】:Eloquent Query with Pivot Table使用数据透视表进行 Eloquent 查询
【发布时间】:2018-12-08 21:14:01
【问题描述】:

我有一个关于如何用 eloquent 生成查询的问题,如果您能提供任何帮助,我将不胜感激。

我的数据库中有 4 个表: 1. 模块 2. 角色 3.module_rol(数据透视表) 4.地区

表格结构:

  1. 模块: id int 名称字符串 区域整数 活跃的布尔

  2. 角色 id int 名称字符串

  3. module_rol rol_id 整数 module_id int

  4. 地区 id int 名称字符串

我需要从模块表中获取所有的值,例如有一些条件..

public function getUserModules($rol, $region)
{
 // Return all modules to which that role is allowed to access and have that region defined
}

在等待一些帮助时,非常感谢您

编辑 1:

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



Schema::create('modules', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('region')->unsigned();
            $table->boolean('active')->default(true);
            $table->timestamps();

            $table->foreign('region')
                ->references('id')->on('regions')
                ->onDelete('cascade');
        });



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



Schema::create('module_rol', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('rol_id');
            $table->integer('module_id');
            $table->timestamps();

            $table->foreign('rol_id')
                ->references('id')->on('roles')
                ->onDelete('cascade');
            $table->foreign('module_id')
                ->references('id')->on('modules')
                ->onDelete('cascade');
        });

【问题讨论】:

  • 你能发布与模型的关系吗?
  • 谢谢!..查看我的编辑

标签: laravel eloquent


【解决方案1】:

您需要使用数据透视表定义 Module 和 Role 之间的 ManyToMany 关系

模块模型

public function roles(){
    return $this->belongsToMany(Role::class, 'module_rol');
}

public function region(){
    return $this->belongsTo(Region::class, 'region');
}

榜样

public function modules(){
        return $this->belongsToMany(Module::class, 'module_rol');
}

获取数据

public function getUserModules($role, $region)
{
 // Return all modules to which that role is allowed to access and have that region defined
    $modules = Module::where('region', $region->id)
                     ->whereHas(['roles' => function($query) use ($role) {
                        return $query->where('role_id', $role->id)
                     }])->get();
    return $modules;
}

详情https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 2015-06-24
    • 2015-09-30
    • 2017-05-05
    • 1970-01-01
    • 2015-12-28
    • 1970-01-01
    相关资源
    最近更新 更多