简体   繁体   English

如何 select 多对多关系表中的数据匹配所需值?

[英]How to select the data from the many-to-many relationship table that matches the desired value?

I'm still new to Laravel.我还是 Laravel 的新手。 I want to select the mainchallengecategories with field role_id on the table that holds the relationship that is equal to 3 because I want only the user who has role_id = 3 to see the mainchallengecategories .我想select具有字段 role_id 的 mainchallengecategories 在表上保持关系等于 3 因为我只希望具有 role_id = 3 的用户查看mainchallengecategories What should I do with my controller?我应该如何处理我的 controller?

I have 4 tables我有 4 张桌子

1. mainchallengecategories 1. 主要挑战类别

id ID name姓名
1 1 Category A甲类
2 2 Category B B类
3 3 Category C类别 C
4 4 Category D D类

2. users 2. 用户

id ID name姓名 role角色
1 1 UserA用户A 1 1
2 2 UserB用户B 2 2
3 3 UserC用户C 3 3
4 4 UserD用户D 3 3

3. roles 3. 角色

id ID name姓名 role角色
1 1 Admin行政 1 1
2 2 staff职员 2 2
3 3 user用户 3 3

4. main_challenge_categories_role 4. main_challenge_categories_role

id ID main_challenge_categories_id main_challenge_categories_id role_id角色 ID
1 1 1 1 1 1
2 2 1 1 1 1
3 3 3 3 2 2
4 4 4 4 3 3

Here is MainChallengeCategories Model这是主要挑战类别 Model

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);
}

User Model用户 Model

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

Role Model角色 Model

public function users(){
    return $this->hasMany(User::class);
}

MainChallengeCategoryRole Model主要挑战类别角色 Model

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 MainChallengeCategoryController

public function create(){

/ $mainchallengecategories = MainChallengeCategoryRole::with('mainchallengecategories') // Eager loading ->where('role_id', '3') ->get(); / $mainchallengecategories = MainChallengeCategoryRole::with('mainchallengecategories') // 渴望加载 ->where('role_id', '3') ->get(); / /

What should I do here in this function????????在这个 function 里我该怎么办??????

    return view('user.addChallenge')
    ->with('mainchallengecategories',$mainchallengecategories);
}

Thank you for everyone's kindness here that I have always received in advance.感谢大家在这里的好意,我一直提前收到。

in Role.php :Role.php中:

public function mainChallengeCategoryRoles(){
  return $this->hasMany(MainChallengeCategoryRole::class, 'role_id', 'id');
}

Get Main challenge category roles of the Role:获取角色的主要挑战类别角色:

$mainchallengecategories = Role::find(3)->mainChallengeCategoryRoles;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM