【问题标题】:Do I always have to call ->count() before ->first() to prevent "No query results for model [Foo]"?我是否总是必须在 ->first() 之前调用 ->count() 以防止“模型 [Foo] 没有查询结果”?
【发布时间】:2014-08-19 09:41:14
【问题描述】:

$this->foo->first()“捕获”任何No query results for model [Foo].“异常”之前,我是否总是需要检查$this->foo->count()

我试过了

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;
}

【问题讨论】:

  • 根据 Laravel 文档调用 ->first() 会返回 NULL 而不是抛出异常。您确定您使用的是->first() 而不是->firstOrFail()。后者会抛出异常。

标签: php exception laravel eloquent


【解决方案1】:

您需要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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    相关资源
    最近更新 更多