2

I am really not getting why this eager loading is not working when I try to return specific columns. This code works perfectly

$user=User::where('userName', $userName)
        ->with('points')
        ->with('examstaken')
        ->with('question')
        /*->with(array('points'=>function($query){
                $query->select('id','points');
         }))*/
         ->get();

This code doesn't wort

$user=User::where('userName', $userName)
        /*->with('points')*/
        ->with('examstaken')
        ->with('question')
        ->with(array('points'=>function($query){
                $query->select('id','points');
         }))
         ->get();

Doesn't work mean, 'points' doesn't return any value while the first one return the values correctly..

Any idea what's wrong with it?

Here is the relation in my user model

  public function points()
{
    return $this->hasMany('App\Points','user_id');
}

Thanks..

1 Answer 1

5

Ok solved it. It seems I have to pass the user_id, the foreign key and then they it will work. Posting it as answer as someone else may get help :)

$user=User::where('userName', $userName)
        /*->with('points')*/
        ->with('examstaken')
        ->with('question')
        ->with(array('points'=>function($query){
                $query->select('user_id','points');
         }))
         ->get();
Sign up to request clarification or add additional context in comments.

1 Comment

if you don't select the keys needed for the relationship, Eloquent wont be able to match up the children to their parents by key

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.