http://laravel.com/docs/4.2/eloquent#dynamic-properties
class Phone extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
$phone = Phone::find(1);
现在,如果我做这样的事情:
echo $phone->user->email;
echo $phone->user->name;
echo $phone->user->nickname;
每次我使用 ->user
动态属性时,Eloquent 都会调用数据库吗?或者这是否足够聪明以在第一次调用时缓存用户?
最佳答案
在您的示例中,$phone
对象的 user
属性将被延迟加载,但只会加载一次。
同时请记住,加载对象后,它不会反射(reflect)对基础表的任何更改,除非您使用 load
方法手动重新加载关系。
下面的代码说明了这个例子:
$phone = Phone::find(1);
// first use of user attribute triggers lazy load
echo $phone->user->email;
// get that user outta here.
User::destroy($phone->user->id);
// echoes the name just fine, even though the record doesn't exist anymore
echo $phone->user->name;
// manually reload the relationship
$phone->load('user');
// now will show null, since the user was deleted and the relationship was reloaded
var_export($phone->user);
关于php - 多次调用 Eloquent 动态属性会多次访问数据库吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28446511/