Home > OS >  Laravel Select Only Child table data and ignore parent data
Laravel Select Only Child table data and ignore parent data

Time:06-15

Hey guys I wanna select from child of child data and I don't need parent data can you please help me?

Team Table Id, Name, manager_id

Manager Table id company_id, user_id

Team Modal

public function manager()
{
   return $this->belongsTo(Manager::class);
}

Manager Modal

public function user()
{
   return $this->belongsTo(User::class);
}

Controller

managerUsers = Team::with('manager.user')
        ->where('company_id', $company->id)
        ->get();

it works fine but it also return team and manager table data I want only user table data

CodePudding user response:

I didnt test this but it should work for you

Here is the documentation for whereHas()

This will find managers who has teams with specific company id

$managerUsers = Manager::whereHas('team', function($query) use ($company) {
    $query->where('company_id', $company->id);
})->with('user')->get();

CodePudding user response:

This is much easier with select method :

Team::with('manager.user')
   ->where('company_id', $company->id)
   ->select(['users.id', 'users.email'])
   ->get();

I'm not sure but this below code may also works :

Team::with('manager.user')
   ->where('company_id', $company->id)
   ->get(['users.id', 'users.name']);

CodePudding user response:

$managerUsers = Team::query()
        ->join('managers', 'managers.id', '=', 'teams.manager_id')
        ->join('users', 'users.id', '=', 'managers.user_id')
        ->select(['users.id','users.first_name', 'users.last_name'])
        ->get();
  • Related