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

标签 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 都会调用数据库吗?或者这是否足够聪明以在第一次调用时缓存用户?

最佳答案

在您的示例中,$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/

相关文章:

AWS 上的 Laravel 调度任务不起作用

Laravel - 如何获取要执行的迁移列表?

php - 带有 if 和 sum 的 Laravel 查询

PHP:使用 strtotime 转换 MySQL UTC 日期以供 pChart 使用

php - 如何在不重新加载页面或计时器的情况下有效地将新数据推送到前端

php - 带约束的 Eloquent 多重嵌套关系

php - 找不到 Illuminate\Routing\Redirector::to ("user/login"的匹配处理程序)

php - Laravel 多重联合

php - Magento CE::首单折扣?

php - 函数内的 while 循环不起作用