问题描述
我还是 Laravel 的新手。我想在包含等于 3 的关系的表上选择具有字段 role_id 的 mainchallengecategories,因为我只想让 role_id = 3 的用户看到 mainchallengecategories .我应该如何处理我的控制器?
我有四张桌子
1.主要挑战类别
id | 姓名 |
---|---|
1 | A 类 |
2 | B 类 |
3 | C 类 |
4 | D 类 |
2.用户
3.角色
4. main_challenge_categories_role
id | main_challenge_categories_id | role_id |
---|---|---|
1 | 1 | 1 |
2 | 1 | 1 |
3 | 3 | 2 |
4 | 4 | 3 |
这是 MainChallengeCategories 模型
public function users(){
return $this->hasMany(User::class);
}
public function roles(){
return $this->belongsToMany(Role::class)->withTimestamps();
}
public function main_challenge_categories_role(){
return $this->hasMany(MainChallengeCategoryRole::class);
}
用户模型
public function roles(){
return $this->belongsTo(Role::class,'role');
}
榜样
public function users(){
return $this->hasMany(User::class);
}
MainChallengeCategoryRole 模型
protected $fillable=['main_challenge_categories_id','role_id'];
public function mainchallengecategories(){
return $this->belongsTo('App\MainChallengeCategories','main_challenge_categories_id');
}
public function roles(){
return $this->belongsTo('App\Role','role_id');
}
MainChallengeCategoryController
public function create(){
/$mainchallengecategories = MainChallengeCategoryRole::with('mainchallengecategories') // 预加载 -> where('role_id','3') ->get();/
return view('user.addChallenge')
->with('mainchallengecategories',$mainchallengecategories);
}
感谢大家对我的好意,我总是提前收到。
解决方法
在Role.php
中:
public function mainChallengeCategoryRoles(){
return $this->hasMany(MainChallengeCategoryRole::class,'role_id','id');
}
获取角色的主要挑战类别角色:
$mainchallengecategories = Role::find(3)->mainChallengeCategoryRoles;