我有一个简单的特性,我用它来总是包含一些软删除的项目:
trait OverrideTrashedTrait {
public static function find($id, $columns = ['*'])
{
return parent::withTrashed()->find($id, $columns);
}
}
但是,自升级到Laravel 5.1以来,这已不再适用。软删除的项目没有出现在get()
列表中,如果我尝试访问我已使用路由模型绑定的页面,我会得到NotFoundHttpException
。
Laravel的升级文档指出:
如果要覆盖自己模型中的
find
方法并在自定义方法中调用parent::find()
,现在应该更改它以在Eloquent查询构建器上调用find
方法:
所以我相应改变了特性:
trait OverrideTrashedTrait {
public static function find($id, $columns = ['*'])
{
return static::query()->withTrashed()->find($id, $columns);
}
}
但似乎无论我在那里写什么,它都不会影响结果。我还尝试将重写find()
方法直接放在模型中,但这似乎也不起作用。如果我写了无效的语法,任何改变的唯一方法。即使我将$id
更改为未被软删除的项目的硬编码ID,我也会得到相同的结果,如果我是尝试dd('sdfg')
,所以我怀疑这个方法甚至被调用。
编辑:如果我手动触发该方法,它就会像预期的那样工作。
我该如何解决这个问题?
答案 0 :(得分:2)
好在这里:
短版:模型绑定不使用find。
更长版本:
/**
* Register a model binder for a wildcard.
*
* @param string $key
* @param string $class
* @param \Closure|null $callback
* @return void
*
* @throws NotFoundHttpException
*/
public function model($key, $class, Closure $callback = null)
{
$this->bind($key, function ($value) use ($class, $callback) {
if (is_null($value)) {
return;
}
// For model binders, we will attempt to retrieve the models using the first
// method on the model instance. If we cannot retrieve the models we'll
// throw a not found exception otherwise we will return the instance.
$instance = new $class;
if ($model = $instance->where($instance->getRouteKeyName(), $value)->first()) {
return $model;
}
// If a callback was supplied to the method we will call that to determine
// what we should do when the model is not found. This just gives these
// developer a little greater flexibility to decide what will happen.
if ($callback instanceof Closure) {
return call_user_func($callback, $value);
}
throw new NotFoundHttpException;
});
}
Illuminate \ Routing \ Router的第931行说它确实:
$instance->where($instance->getRouteKeyName(), $value)->first()
它使用where中使用的模型中的键并加载第一个结果。