检查模型是否存在

时间:2016-07-26 15:38:57

标签: php laravel laravel-5

当在Laravel中搜索应该是一个非常基本和常见的测试时,似乎存在很多关于如何正确检查天气或者模型是否存在的混淆,然后如果确实如此则对模型做一些事情。在通过stackoverflow,laracasts和laravel文档本身进行搜索时,它不再变得清晰。例如,如果我运行此查询,

$restaurant = Restaurant::find($input["restaurant_id"]);

有各种堆栈溢出帖子可以让我检查count(),使用看起来不一致的exists()方法,或者使用抛出异常的firstOrFail()。我想做的就是像上面那样进行一次调用,检查$ restaurant是否是一个有效的模型,然后做一些事情。在我的情况下不需要例外,我不想在使用count()或exists()之后再次运行查询。该文档没有任何有用的信息,它允许返回4种不同的变量类型,而不提及哪种情况会触发哪种返回。有没有人对这个话题有很好的处理?

Laravel checking if record exists

Eloquent ->first() if ->exists()

https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html#method_find

3 个答案:

答案 0 :(得分:5)

您不需要运行任何其他查询。如果记录不存在,find()将返回null。您可以使用简单的if来检查:

if($restaurant = Restaurant::find($input["restaurant_id"]) {
    // Do stuff to $restaurant here
}

答案 1 :(得分:0)

您也可以使用

$restaurant = Restaurant::findOrFail($input["restaurant_id"]);
  

有时,如果找不到模型,您可能希望抛出异常。这在路线或控制器中特别有用。 findOrFail和firstOrFail方法将检索查询的第一个结果。但是,如果未找到任何结果,将抛出Illuminate \ Database \ Eloquent \ ModelNotFoundException:

来自:https://laravel.com/docs/5.1/eloquent

答案 2 :(得分:0)

在关于你的问题的laravel文档中非常清楚,find(),first(),get(),如果模型不存在则返回null,

   $model = Restaurant::find(111); // or
   $model = Restaurant::where('id',111)->first();
   if(!$model){ //if model not exist, it means the model variable is null
    }