多次调用 Eloquent 动态 属性 会多次访问数据库吗?

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

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

另外请记住,加载对象后,它不会反映对基础 table 的任何更改,除非您使用 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);