我对如何雄辩地生成查询存在疑问,希望您能提供帮助。
我的数据库中有4个表: 1.模块 2.角色 3. module_rol(数据透视表) 4.地区
表的结构:
个模块: id int 名称字符串 区域int 主动布尔
角色 id int 名称字符串
module_rol rol_id int module_id int
地区 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');
});
答案 0 :(得分:0)
您需要使用数据透视表定义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