deepu07's avatar
Level 11

Select specific columns in hasMany relationship

//Department Model

public function users()
{
     return $this->hasMany(User::class, 'department_id', 'id');
}

in controller doing like this

$department_users = Department::with(['users' => function($query) {
        $query->select(['id', 'user_name', 'email']);
  }])->get();

somehow I'm getting empty users in results. How can I get selected column values in this case? any help that would be great. Thanks!

0 likes
4 replies
faridbabayev's avatar

@deepu07 you can use select with hasMany method

public function users()
{
     return $this->hasMany(User::class, 'department_id', 'id')->select('id', 'user_name', 'email');
}
blaubit's avatar

@MamoonaShuja The foreign key column must be included, otherwise the relations is not working. So in the above suggestion, the select array should include 'user_id'.

Sergiu17's avatar

You also have to include the foreign key

$department_users = Department::with(['users' => function($query) {
  $query->select(['id', 'department_id',  'user_name', 'email']);
}])->get();
// or
Department::with('users:id,department_id,user_name,email')->get();
1 like

Please or to participate in this conversation.