如何在Laravel中加载,同时找到一个特定的条目

时间:2013-03-12 21:26:38

标签: php laravel eloquent laravel-3

我想用他们的用户个人资料急切地加载特定用户。我的表和类分别称为用户和用户。我的个人资料表和类是user_profiles和UserProfile。

这就是我正在尝试的但它似乎无法正常工作

return User::with('user_profiles')->find(1);

2 个答案:

答案 0 :(得分:3)

您还需要在User课程中定义relationship method。类似的东西:

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

然后引用关系方法的名称:

User::with('profile')->get()

答案 1 :(得分:0)

我发现以下代码对于从一个模型实例中检索所有属性非常有用。

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

返回此类数组

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

添加了:

这会很慢,因为->get()会从数据库中检索所有数据。

所以

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