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