Home > front end >  How to obtain three level relationship in LARAVEL?
How to obtain three level relationship in LARAVEL?

Time:04-12

I have 3 tables, User, Group and GroupUser. I want to get user details (user table) who are added in group. Here is the talbe structure i am following.

user
 -------------- ---------------------- 
| id    | name      | user_statu      |
 -------------- ---------------------- 
| 1     | John doe  | ofline          |
 -------------- ---------------------- 
| 2     | John carry| away            |
 -------------- ---------------------- 
| 3     | jimn carry| online          |
 -------------- ---------------------- 
| 4     | adward    | online          |
 -------------- ---------------------- 


group
 -------------- ---------------------- 
| id    | title     | status          |
 -------------- ---------------------- 
| 1     | group1    | actie           |
 -------------- ---------------------- 
| 2     | group2    | acrive          |
 -------------- ---------------------- 


group_users
 -------------- ------------------- 
| id    | user_id   | group_id     |
 -------------- ------------------- 
| 1     | group1    | 1            |
 -------------- ------------------- 
| 2     | group2    | 1            |
 -------------- -------------------  

Model

Group.php

public function users() {
    return $this->hasMany('App\Models\GroupUser', 'group_id');
}

What i am trying is:

$group = Group::with("users")->where([
                        ['id', '=', $user_id],
                        ['status', '=', 1],
                    ])->first();
$group->users

I am getting

"users": [
    {
        "id": 1,
        "user_id": 237,
        "group_id": 1,
        "status": 1,
    },

i also want to get user name along.

Please correct me. Thank you.

CodePudding user response:

I think what you want to do here is many-to-many relationships (https://laravel.com/docs/9.x/eloquent-relationships#many-to-many)

In your model Group.php:

public function users() {
    return $this->belongsToMany('App\Models\User', 'group_users', 'group_id', 'user_id');
}

Then when you do $group->users, it will contain the model User not GroupUser. You can now get the name from here.

CodePudding user response:

use code :

public function users() {
    return $this->belongsToMany(User::class, 'group_users', 'group_id', 'user_id');
}
  • Related