2

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.

1
  • What does your Question model look like? It might be helpful to see the relationship between the question and the asker. Commented Dec 21, 2016 at 17:36

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Do you get null for relation? Does it work if you remove the closure? Is question_id correct name of foreign key?
yeah null for ralation and it works and askedby is the foreign key. Thanks for the effort.
1

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 Comments

So, you didn't actually try my code, but said it didn't work. select for Question model was removed so my code should work.
not really. I tried then the error stated as askedby is not found in the TABLE(i also tried the other key) and then thought including it in the select statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.