对Eloquent动态属性的多次调用会多次命中数据库吗


Will multiple calls to Eloquent dynamic property hit the database multiple times?

http://laravel.com/docs/4.2/eloquent#dynamic-属性

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属性将延迟加载,但只加载一次。

还要记住,一旦加载了对象,它就不会反映对基础表的任何更改,除非您使用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);