Laravel Moloquent. Add projection to related model

596 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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();
1
On

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

Model1::with(['model2' => function($query){
    $query->select('column1','column2');
}])->get();