在我可以$this->foo->first()
“捕获”之前,我是否总是必须检查$this->foo->count()
"任何 没有模型 [Foo] 的查询结果。
“异常”?
我试过了
public function hasValid($model)
{
try {
return $this->$model()->firstOrFail()->expiration > date('Y-m-d') ? true : false;
} catch(ModelNotFoundException $e) {
return false;
}
}
但是当查询返回一个空查询集时,我仍然得到No query results for model [Foo].
。
我并不总是想在任何 $this->foo->first()
调用前加上一个 $this->foo->count()
调用只是为了检查这个。必须有一个 DRYer 解决方案。
我认为这是迄今为止最干的:
public function hasValid($model)
{
$model = $this->$model()->first();
return isset($model) && $model->expiration > date('Y-m-d') ? true : false;
}
最佳答案
您需要use
语句或异常的完整命名空间:
use Illuminate\Database\Eloquent\ModelNotFoundException;
// or:
catch(Illuminate\Database\Eloquent\ModelNotFoundException $e)
您还可以定义默认处理程序,因此您可以简单地执行此操作:
public function hasValid($model)
{
return ($this->$model()->firstOrFail()->expiration > date('Y-m-d')) ? true : false;
}
// in global.php or wherever, something like this:
App::error(function(Illuminate\Database\Eloquent\ModelNotFoundException $exception, $code)
{
Log::error($exception);
return Response::make('Not found', 404);
});
关于php - 我是否总是必须在 ->first() 之前调用 ->count() 来防止 "No query results for model [Foo]"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25380208/