php 检查 Eloquent 查询是否不返回任何答案的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22993972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:25:18  来源:igfitidea点击:

What is the best way to check if an Eloquent query returns no answer?

phplaravel

提问by Garry Pettet

I'm using Laravel 4. Say I have an Eloquent model (Patient) and I want to get a patient with the name Bob, I would do this:

我正在使用 Laravel 4。假设我有一个 Eloquent 模型(患者)并且我想要一个名为 Bob 的患者,我会这样做:

$patient = Patient::where('name', '=', 'Bob');

What is the best way to check to see if $patient is a valid record?

检查 $patient 是否为有效记录的最佳方法是什么?

回答by Jake Wilson

If the database query does not find any matching results, it returns null. Therefore...

如果数据库查询没有找到任何匹配的结果,则返回null。所以...

$patient = Patient::where('name','=','Bob')->first();

if ( is_null($patient) ) {
  App::abort(404);
}

(Note: in your original question you forgot ->first()(or ->get()) in your query. Don't forget that or else you will get an Eloquent object instead of a result.)

(注意:在您的原始问题中,您在查询中忘记了->first()(或->get())。不要忘记这一点,否则您将获得 Eloquent 对象而不是结果。)

回答by Jarek Tkaczyk

use this:

用这个:

$patient = Patient::where('name', '=', 'Bob')->firstOrFail();

it will return Eulqouent model on success or throw ModelNotFoundException upon failure.

它会在成功时返回 Eulqouent 模型或在失败时抛出 ModelNotFoundException。

回答by Michael Oliver

I know this is old, but this came up as the 2nd google hit on a search, so . . . for cases where you are not expecting one record or cannot use ->firstOrFail()(my use case is an async typeahead api that returns up to 10 results) the only thing that worked for me was count():

我知道这是旧的,但是这是在第二次谷歌搜索时出现的,所以 . . . 对于您不希望有一条记录或无法使用的情况->firstOrFail()(我的用例是一个异步 typeahead api,它最多返回 10 个结果),唯一对我有用的是 count():

$patient = Patient::where('name', '=', 'Bob')->get(); //you could have more than one bob
if (!count($patient)) {
    return 'No records found';
}

回答by Niamat Zawad

$patient = Patient::where('name','Bob')->get();

if ( $patient->isEmpty() ) {
  return response(['error' => 'Record not found'], 404);
}

回答by Ryan

Something like Patient::where('name', '=', 'Bob')->exists()may work. It will return a boolean.

类似的东西Patient::where('name', '=', 'Bob')->exists()可能会起作用。它将返回一个布尔值。

回答by Angga Ari Wijaya

Just use empty()from native php will solve everything, if object null it will return true, if laravel's collectionfrom query builder is empty (but initialized) it will return true too.

仅使用empty()来自本机 php 就可以解决所有问题,如果对象为 null,它将返回 true,如果collection来自查询构建器的laravel为空(但已初始化),它也将返回 true。

$contributor = Contributor::whereVendor('web')->first();
if(empty($contributor)){
   ...
}

回答by Amit Shah

use findOrFail($id)in case of you are passing idparameter to fetch a single record

findOrFail($id)在您传递id参数以获取单个记录的情况下使用

I ended up on this while seeking solution of ::find($id)->firstOrFailsyntax which is error-full.

我在寻求::find($id)->firstOrFail错误的语法解决方案时最终解决了这个问题。

$patient = Patient::findOrFail($id);