How to select specific column from model while using eager loading : laravel

776 Views Asked by At

I have successfully retrieved data using eager loading as following:

$var = Question::with(['asker'=>function($query){
        $query->select('id','username');
    }])->get();

The problem is that I am unable to choose specific columns from the model Question. I have tried the following:

$var = Question::select('q_id','title')->with(['asker'=>function($query){
        $query->select('id','username');
    }])->get();

$var = Question::with(['asker'=>function($query){
        $query->select('id','username');
    }])->get(['q_id','title']);

In both cases, it returned null value for asker while choosing q_id and title.

2

There are 2 best solutions below

2
On BEST ANSWER

I had to include the foreign key while selecting data from the model.

$var = Question::select('q_id','title','askedby')->with(['asker'=>function($query){
    $query->select('id','username');
}])->get();

The extra field 'askedby' had to be included. Thanks for the clue.

2
On

You also need to select foreign key, so Eloquent could find relation:

$var = Question::with(['asker' => function($query){
    $query->select('id', 'username', 'question_id');
}])->get();