我正在使用 Laravel 5 构建一个简单的时间跟踪应用程序,其中我有两个 Laravel 模型,一个称为“用户”,一个称为“周”
关系很简单:
周.php:
public function user()
{
return $this->belongsTo('App\User');
}
用户.php:
function weeks()
{
return $this->hasMany('App\Week');
}
现在,User.php 文件还有一个名为“getCurrentWeek()”的简单辅助/新颖函数,顾名思义,它返回当前周
function getCurrentWeek()
{
$possibleWeek = $this->weeks->sortByDesc('starts')->all();
if(count($possibleWeek) != 0)
{
return $possibleWeek[0];
}
else
{
return null;
}
}
我的问题是:如果我为用户创建第一周并将其附加/关联到用户,如下所示:
$week = new Week;
//Omitted: Setting so attributes here ...
$week->user_id = $user->id;
$weeks->save()
$user->weeks()->save($week);
然后调用$user->getCurrentWeek();
方法,该方法返回null
,虽然已经创建了新的一周,但与用户相关已保存到数据库中。在我看来,getCurrentWeek()
的预期行为是返回新创建的周。
我在这里对 Eloquent 有什么误解/做错了什么?
最佳答案
关系属性在第一次访问时被延迟加载。加载后,它们不会自动刷新关系中添加或删除的记录。
因为您的 getCurrentWeek()
函数使用了关系属性,所以这段代码可以工作:
$week = new Week;
// setup week ...
$user->weeks()->save($week);
// $user->weeks attribute has not been accessed yet, so it will be loaded
// by the first access inside the getCurrentWeek method
dd($user->getCurrentWeek());
但是,这段代码将不起作用:
// accessing $user->weeks lazy loads the relationship
echo count($user->weeks);
// relate a new record
$week = new Week;
// setup week ...
$user->weeks()->save($week);
// $user->weeks inside the method will not contain the newly related record,
// as it has already been lazy loaded from the access above.
dd($user->getCurrentWeek());
您可以修改 getCurrentWeek()
方法以使用关系方法 ($this->weeks()
) 而不是属性 ($this ->weeks
),这将始终命中数据库,或者您可以在添加或删除记录后重新加载关系(使用 load()
方法)。
更改 getCurrentWeek()
方法以使用关系方法 weeks()
(@Bjorn 提供的更新方法)
function getCurrentWeek()
{
return $this->weeks()->orderBy('starts', 'desc')->first();
}
或者,使用 load()
方法刷新关系:
// accessing $user->weeks lazy loads the relationship
echo count($user->weeks);
// relate a new record
$week = new Week;
// setup week ...
$user->weeks()->save($week);
// reload the weeks relationship attribute
$user->load('weeks');
// this will now work since $user->weeks was reloaded by the load() method
dd($user->getCurrentWeek());
关于php - 保存后的 Laravel 关系可用性(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39520072/