mat*_*hew 30 php unit-testing laravel eloquent laravel-4
在我的一些测试中,我有一个我创建的用户模型,并运行一些需要保存某些属性的方法.在rails中,我通常会调用类似于user.reload
从数据库中重新填充属性的东西.
laravel有办法做到这一点吗?我通读了api并找不到适合它的方法:http://laravel.com/api/4.1/Illuminate/Database/Eloquent/Model.html有关"正确"方法的任何想法吗?
orr*_*rrd 52
有一个承诺提交4.0分支在八月作出补充重载()方法,但到目前为止,还没有被合并到新的Laravel分支机构.
但是...... Laravel 5提供了一个"fresh()"方法,它将返回当前模型的新实例.一旦您使用Laravel 5.0或更高版本,您可以重新加载这样的模型:
$model = $model->fresh();
Run Code Online (Sandbox Code Playgroud)
请注意,fresh()不直接更新现有的$ model,它只返回一个新实例,这就是我们需要使用"$ model ="的原因.它还接受一个参数,它是一个你希望它急切加载的关系数组.
如果您尚未使用Laravel 5但需要相同的功能,则可以将此方法添加到模型中:
public function fresh(array $with = array())
{
$key = $this->getKeyName();
return $this->exists ? static::with($with)->where($key, $this->getKey())->first() : null;
}
Run Code Online (Sandbox Code Playgroud)
Jef*_*ett 40
感谢PR#19174,因为5.4.24是refresh
方法.
$model->refresh();
Run Code Online (Sandbox Code Playgroud)
这样您就不必处理重新分配,如该fresh
方法的其他答案中所示,如果您想要刷新已传递到另一个方法的模型,这通常没有用,因为变量赋值将超出范围调用上下文以便稍后使用.
iga*_*ter 11
refresh()
是一个可变操作:它将从数据库中重新加载当前模型实例。fresh()
是一个不变的操作:它从数据库中返回一个新的模型实例。它不会影响当前实例。// Database state:
$user=User::create([
'name' => 'John',
]);
// Model (memory) state:
$user->name = 'Sarah';
$user2 = $user->fresh();
// $user->name => 'Sarah';
// $user2->name => 'John'
$user->refresh();
// $user->name => 'John'
Run Code Online (Sandbox Code Playgroud)
我也看不到它.看起来你必须:
$model = $model->find($model->id);
Run Code Online (Sandbox Code Playgroud)
您也可以自己创建一个:
public function reload()
{
$instance = new static;
$instance = $instance->newQuery()->find($this->{$this->primaryKey});
$this->attributes = $instance->attributes;
$this->original = $instance->original;
}
Run Code Online (Sandbox Code Playgroud)
刚刚在这里进行了测试,它看起来很有效,不知道这有多远,但Eloquen是一个非常大的课程.
归档时间: |
|
查看次数: |
26651 次 |
最近记录: |