简体   繁体   English

检查Eloquent查询是否没有回答的最佳方法是什么?

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

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.说我有一个雄辩的模型(患者),我想找一个名叫Bob的病人,我会这样做:

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

What is the best way to check to see if $patient is a valid record? 检查$ patient是否为有效记录的最佳方法是什么?

If the database query does not find any matching results, it returns null . 如果数据库查询未找到任何匹配结果,则返回null Therefore... 因此...

$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对象而不是结果。)

use this: 用这个:

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

it will return Eulqouent model on success or throw ModelNotFoundException upon failure. 它会在成功时返回Eulqouent模型,或者在失败时抛出ModelNotFoundException。

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() (我的用例是一个async typeahead api,最多返回10个结果),对我来说唯一有效的是count():

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

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

Something like Patient::where('name', '=', 'Bob')->exists() may work. Patient::where('name', '=', 'Bob')->exists()可能会起作用。 It will return a boolean. 它将返回一个布尔值。

Just use empty() from native php will solve everything, if object null it will return true, if laravel's collection from query builder is empty (but initialized) it will return true too. 只需使用本机php中的empty()将解决所有问题,如果对象为null则返回true,如果laravel的查询构建器collection为空(但已初始化),它也将返回true。

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

use findOrFail($id) in case of you are passing id parameter to fetch a single record 如果您正在传递id参数以获取单个记录,请使用findOrFail($id)

I ended up on this while seeking solution of ::find($id)->firstOrFail syntax which is error-full. 我在寻找解决方案的同时找到了这个::find($id)->firstOrFail语法,它是错误的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM