关系属性在第一次访问时会延迟加载。加载后,它们不会自动刷新关系中添加或删除的记录。
自从你的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()
method:
// 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());