Laravel 9 Backpack 5:基于双表添加BaseClause过滤企业列表
解决方案
1. 修正User模型的关联关系
你的User模型中companies关联的外键顺序错误,会导致关联查询无法正确匹配,修改如下:
// User.php public function companies() { // 正确参数顺序:关联模型、中间表、当前模型(User)在中间表的外键、关联模型(Company)在中间表的外键 return $this->belongsToMany(\App\Models\Company::class, 'companies_users', 'user_id', 'company_id'); }
2. 在CompanyCrudController中添加过滤逻辑
替换原来的默认企业过滤代码,用Laravel查询构建器组合两个过滤条件:
// CompanyCrudController.php public function setup() { // ... 保留原有的其他setup配置代码 // 移除原默认企业过滤行:$this->crud->addClause('WHERE', 'company_id', backpack_user()->default_company); // 添加新的权限过滤条件 $currentUserId = backpack_user()->id; $this->crud->query->where(function ($query) use ($currentUserId) { // 条件1:用户是企业创建者(匹配Companies表的user_id) $query->where('user_id', $currentUserId) // 条件2:用户是受邀管理者(通过关联表Companies_Users匹配) ->orWhereHas('users', function ($subQuery) use ($currentUserId) { $subQuery->where('user_id', $currentUserId); }); }); }
逻辑说明
where('user_id', $currentUserId):直接筛选出当前用户创建的企业;orWhereHas('users', ...):通过Company模型定义的users关联,检查当前用户是否在该企业的受邀管理者列表中;- 外层包裹的匿名函数确保两个条件为或关系,满足任意一个即可显示对应企业。
额外验证
确保CompanyUser模型(对应companies_users中间表)配置正确:
// app/Models/CompanyUser.php namespace App\Models; use Illuminate\Database\Eloquent\Model; class CompanyUser extends Model { protected $table = 'companies_users'; protected $fillable = ['company_id', 'user_id']; public $timestamps = false; // 若中间表无created_at/updated_at字段,需添加此行 }
内容的提问来源于stack exchange,提问作者George Dobre
相关产品推荐
相关产品推荐

