0

How do write this eloquent query in Laravel so that it eager loads with() the relationship model in this example between a User model and Profile model? I was trying to avoid 2 separate queries.

I feel I am close, but somethings not quite right.

$author = User::where('id', $id)->with('profile')->get();

The collection is returning the user details correctly. But it's showing the profile relationship as null.

  #relations: array:1 [▼
    "profile" => null
  ]

I believe I have things setup correctly with a User model and a Profile needed relationships.

User.php

public function profile()
{
    return $this->hasOne('App\AuthorProfile', 'user_id');
}

AuthorProfile.php

public function user()
{
    return $this->belongsTo('App\User');
}

3 Answers 3

2

Assuming for AuthorProfile model table you have record with id of user it should be fine.

However you wrote:

I was trying to avoid 2 separate queries.

Well, it's not true, if you have single record, eager loading won't help you at all. In this case 2 queries will be execute - no matter if you use eager loading or you won't.

Eager loading would help if you had multiple users and for each of them you wanted to load profile, but if you have single record it won't change anything.

Additionally instead of:

$author = User::where('id', $id)->with('profile')->get();

you should rather use:

$author = User::with('profile')->find($id);

because you expect here single user.

Sign up to request clarification or add additional context in comments.

Comments

0
$users = User::with('profile')->find($id);

Comments

0

Your model should be like this.The User_id on the profile table and id on the user table

public function profile()
{
    return $this->hasOne('App\AuthorProfile', 'user_id','id');
}

Comments

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.