1

I have a query with relation.

$dbQuery = $this->someModel
    ->where('user_id', '<>', Auth::id())
    ->with(['questions'])
    ->get(['title', 'status', 'expired_at']);

The list of fields in get() method define the list of selected fields for the top level of selected data. But I need also add a projection to questions relation. How can I select only questions._id and questions.description?

I've tried to add this to get() list, but it not works in this way.

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
Denys Siebov
  • 198
  • 4
  • 16

2 Answers2

3

You can use a closure with with for selecting just certain columns:

Model1::with(['model2' => function($query){
    $query->select('column1','column2');
}])->get();
namelivia
  • 2,657
  • 1
  • 21
  • 24
  • When tried with `select` as you mentioned it returns an empty array everytime. May be Moloquent does not suports `select`, don't know. – Denys Siebov Apr 09 '19 at 09:33
0

I've found a solution that works for me based on @namelivia answer. It now works for me with select, but it works with project.

Model1::with(['model2' => function($query){
    $query->project([
        'column1' => 1,
        'column2' => 1,
        'foreign_key' => 1 /* can not be excluded. */         
    ]);
}])->get();
Denys Siebov
  • 198
  • 4
  • 16