PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, April 18, 2022

[FIXED] How to obtain three level relationship in LARAVEL?

 April 18, 2022     laravel, laravel-8, php     No comments   

Issue

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.


Solution

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.



Answered By - aceraven777
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing