3

I want to eagerly load a specific user, with their User Profile. My table and class is called users and User respectively. My Profiles table and class is user_profiles and UserProfile.

This is what I'm trying but it doesn't seem to work

return User::with('user_profiles')->find(1);
juco
  • 6,331
  • 3
  • 25
  • 42
WebDevDude
  • 829
  • 1
  • 8
  • 14
  • FYI, there is no reason to use eager loading (with "with()") if you're just retrieving one record with find() anyway. The database queries end up being exactly the same. Eager loading is only beneficial if you're retrieving multiple records from the database. – orrd Jan 13 '17 at 04:16

2 Answers2

3

You also need to define a relationship method in your User class. Something like:

public function profile()
{
   return $this->belongs_to('UserProfile');
}

You then reference the name of relationship method:

User::with('profile')->get()
juco
  • 6,331
  • 3
  • 25
  • 42
  • That worked. I had done that, but I had the function named as userProfile, so changing it to just profile helped. I didn't realize that it used the function's name. – WebDevDude Mar 12 '13 at 22:40
0

I found the following code is useful for retrieving all properties from one model instance.

User::with('posts')->get()->find(1);

returns such array

id: 1,
name: 'john',
posts: [
  {
    id: 1,
    title: 'something',
  }
]

Added:

This will be slow because ->get() retrives all data from DB.

so

User::with('posts')->find(1)

Kazuya Gosho
  • 996
  • 13
  • 14