Php 如何在Laravel中快速加载,同时查找特定条目
我想急切地加载一个特定的用户,以及他们的用户配置文件。我的表和类分别称为users和User。我的Profiles表和类是user\u Profiles和UserProfile 这是我正在尝试的,但似乎不起作用Php 如何在Laravel中快速加载,同时查找特定条目,php,laravel,eloquent,laravel-3,Php,Laravel,Eloquent,Laravel 3,我想急切地加载一个特定的用户,以及他们的用户配置文件。我的表和类分别称为users和User。我的Profiles表和类是user\u Profiles和UserProfile 这是我正在尝试的,但似乎不起作用 return User::with('user_profiles')->find(1); 您还需要在User类中定义一个。比如: public function profile() { return $this->belongs_to('UserProfile');
return User::with('user_profiles')->find(1);
您还需要在User
类中定义一个。比如:
public function profile()
{
return $this->belongs_to('UserProfile');
}
然后引用关系方法的名称:
User::with('profile')->get()
我发现以下代码对于从一个模型实例检索所有属性非常有用
User::with('posts')->get()->find(1);
返回这样的数组
id: 1,
name: 'john',
posts: [
{
id: 1,
title: 'something',
}
]
增加:
这会很慢,因为->get()
会从数据库中检索所有数据
所以
User::with('posts')->查找(1)
有效。我已经这样做了,但是我有一个名为userProfile的函数,所以将它改为profile会有所帮助。我没有意识到它使用了函数名。仅供参考,如果您只是使用find()检索一条记录,那么没有理由使用即时加载(使用“with()”)。数据库查询结果完全相同。只有在从数据库检索多条记录时,即时加载才有用。