I'm still new to 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. What should I do with my controller?
I have 4 tables
1. mainchallengecategories
id | name |
---|---|
1 | Category A |
2 | Category B |
3 | Category C |
4 | Category D |
My Answer:
2. roles
id
name
1
Admin
2
Moderator
3
User
3. users
id
name
role_id
1
John
3
2
Jane
2
3
Doe
3
4. mainchallengecategory_user
id
mainchallengecategory_id
user_id
role_id
1
1
1
3
2
2
1
3
3
3
2
2
4
4
3
3
To select the mainchallengecategories with field role_id on the table that holds the relationship that is equal to 3, you can use the following code in your controller:
php
$mainchallengecategories = MainChallengeCategory::whereHas('users', function($query) {
$query->where('role_id', 3);
})->get();
This code uses the `whereHas` method to filter the `MainChallengeCategory` model based on the relationship with the `users` table where the `role_id` is equal to 3. This will only return the mainchallengecategories that are associated with users who have a role_id of 3.
Make sure to adjust the model and relationship names according to your actual code structure.
Rate this post
4 of 5 based on 4430 votesComments