Reputation: 184
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
.
Upvotes: 2
Views: 754
Reputation: 184
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.
Upvotes: 1
Reputation: 163768
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();
Upvotes: 4