Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel Relationship issue with user Model

I am using laravel and I am trying to create an relationship with user model

User Table

id name
1 xyz
2 abc
3 zzz
4 yyy

users_teamleaders table

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

user_id team_user_id
1 2
1 3
4 1
4 2

Inside User Model I have written

public function userteamdata()
{
  return $this->hasMany(UserTeamLeaders::class);
}

Inside UserTeamLeaders Model I have witten

public function distributorUser()
{
   return $this->belongsTo(User::class, 'team_user_id', 'id');
}

I want to fetch the details of user with relation user data also

like example
{
‘id’ : 1,
‘name’ : ‘xyz’
‘userteamdata’: [
{
‘id’ : 2,
‘name’ : ‘abc’
},
{
‘id’ : 3,
‘name’ : ‘zzz’
}
];
}

is there any way out to fetch like this using relation or I have to do it using query ?

>Solution :

At the basic implementation, it can be done something like

$user_id = 1;

// Fetch the user with the related 'userteamdata' and the related 'distributorUser' of each 'userteamdata'
$user = User::with('userteamdata.distributorUser')->find($user_id);

// Transform the 'userteamdata' relationship data
$user->userteamdata = $user->userteamdata->map(function ($userTeamLeader) {
    return [
        'id' => $userTeamLeader->distributorUser->id,
        'name' => $userTeamLeader->distributorUser->name,
    ];
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading