Laravel 查询生成器firstOrFail()?

giò*_*giò 1 php sql orm laravel

当我使用查询生成器时,我总是发现自己在做这样的事情:

    $item = \DB::table('table')->where('slug',$slug)->first();

    if ($item===null)
        throw \Exception('Not found');
Run Code Online (Sandbox Code Playgroud)

如果有像 Eloquent 这样的firstOrFail(),这个问题就很容易解决:

$item = \DB::table('table')->where('slug',$slug)->firstOrFail();
Run Code Online (Sandbox Code Playgroud)

Eloquent 是唯一的使用方法firstOrFail()吗?查询生成器是否允许这样的事情?

Jos*_*ber 5

您可以通过宏将其自己添加到查询生成器中:

DB::query()->macro('firstOrFail', function () {
    if ($record = $this->first()) {
        return $record;
    }

    throw new Exception('No records found');
});
Run Code Online (Sandbox Code Playgroud)

然后你可以像使用 Eloquent 一样使用它:

$item = DB::table('table')->where('slug', $slug)->firstOrFail();
Run Code Online (Sandbox Code Playgroud)

  • 请记住,如果未找到模型,eloquent 会抛出 ModelNotFound 异常。这意味着未处理的异常将返回 404,而使用此异常将返回 500。 (2认同)