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

时间:2015-02-11 04:14:54

标签: php laravel laravel-4 eloquent

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是否会进行数据库调用?或者这是否足够聪明,可以在第一次通话时缓存用户?

1 个答案:

答案 0 :(得分:7)

在您的示例中,user对象上的$phone属性将被延迟加载,但只会加载一次。

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