D'Arcy Rail-Ip
D'Arcy Rail-Ip

Reputation: 11975

How to get specific columns on "with" relation and main collection?

I know that I can do this:

User::with(array('project' => function($query){
   $query->select('title');
}))->get()

And that I can do this:

User::get(['name', 'title', 'status', 'created_at']);

How can I merge them? This doesn't work:

User::with(array('project' => function($query){
    $query->select('title');
}))->get(['name', 'title', 'status', 'created_at'])

Ideally, my results are formed as:

[{
  _id: 'ID',
  name: 'NAME',
  title: 'TITLE',
  status: 'STATUS',
  created_at: 'CREATED_AT',
  project: {
      _id: 'ID',
      title: 'PROJECT TITLE'
  }
  } ... ]

Upvotes: 1

Views: 47

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25936

You have to select the relationship's foreign and local key:

User::with(['project' => function($query) {
    $query->select('_id', 'title');
}])->get(['name', 'title', 'status', 'created_at', 'project_id'])

In Laravel 5.5+, you can use this:

User::with('project:_id,title')
    ->get(['name', 'title', 'status', 'created_at', 'project_id'])

Upvotes: 5

Related Questions