Laravel查询生成器firstOrFail()? [英] Laravel Query Builder firstOrFail()?

查看:118
本文介绍了Laravel查询生成器firstOrFail()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I use Query Builder I Always find myself doing something like this:

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

    if ($item===null)
        throw \Exception('Not found');

如果存在像Eloquent这样的firstOrFail(),则可以轻松解决此问题:

This could be easly solved if there were a firstOrFail() like Eloquent:

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

口才是使用firstOrFail()的唯一方法吗?查询生成器是否允许类似这样的内容?

Is Eloquent the only way to use firstOrFail()? Does Query Builder allow something like this?

推荐答案

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

You can add it yourself to the query builder, via a macro:

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

    throw new Exception('No records found');
});

然后,您可以像雄辩一样使用它:

Then you can use it the same way you do Eloquent:

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

这篇关于Laravel查询生成器firstOrFail()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆