为什么我在 laravel 中没有得到模型的查询结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52471960/
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-09-14 18:04:57  来源:igfitidea点击:

why i am getting No query results for model in laravel?

laravellaravel-5laravel-5.2laravel-5.1

提问by ravi

When i search by city name which is available in my database table it will show the result but when i search by unknown city which is not available in my database table it says -No query results for model [App\City].i am sharing you the code and screenshot see error screenshotactually i want to redirect to 401 page if the city is not found in my database table

当我按数据库表中可用的城市名称搜索时,它会显示结果,但是当我按数据库表中不可用的未知城市搜索时,它会显示 -模型 [App\City] 没有查询结果。我正在与您分享代码和屏幕截图查看错误屏幕截图实际上我想重定向到 401 页面,如果在我的数据库表中找不到该城市

Here is my route

这是我的路线

Route::get('teacher-jobs-by-city/{city}','TeacherJobsController@by_location');

Route::get('teacher-jobs-by-city/{city}','TeacherJobsController@by_location');

Here is my function

这是我的功能

public function by_location($location_id='') {

公共函数 by_location($location_id='') {

$data= array();
$location = City::where('slug',$location_id)->where('status','1')->firstOrFail();
$items= Subject::orderBy('id','asc')->get();
$data['location']=$location;

      //$subjects = [''=>'Select Subject'] + Subject::lists('subject_title','id')->toArray();
      //$city = [''=>'Select City'] + City::lists('name','id')->toArray();
        $active_class ='Select Subject to see job Openings';
        return view('frontend.teacherjobs.by_location',compact('active_class','data','items'));

    }

回答by Elias Soares

That's because you are using the firstOrFail()method, that as named, fails if theres no result by throwing an Exception that will be redered as "No query results for model ..." message.

那是因为您正在使用该firstOrFail()方法,该方法在没有结果的情况下失败,该异常将被重新标记为“模型没有查询结果...”消息。

If you want to it don't fail, you can:

如果你不想失败,你可以:

  1. Surround your query with a try-catch block, handling the exception and return some message
  2. Replace the firstOrFail()method by first()
  1. 用 try-catch 块包围您的查询,处理异常并返回一些消息
  2. firstOrFail()方法替换为first()

回答by Yves Kipondo

You can handle that kind of error by modifying the way Illuminate\Database\Eloquent\ModelNotFoundExceptionException are handle. In the App\Exceptions\Handlerclass change the render method to look like this

您可以通过修改Illuminate\Database\Eloquent\ModelNotFoundException处理异常的方式来处理这种错误。在App\Exceptions\Handler类中将渲染方法更改为如下所示

public function render($request, Exception $exception)
{
    if($exception instanceof ModelNotFoundException){
        return redirect("/error_page", 401)->with('error', $e->getMessage());
    }
    return parent::render($request, $exception);
}

Within the redirect your must put the route to which you want to be redirected, I put /error_pagejust for sample purpose. You can learn more on Error Handling'

在重定向中,您必须放置要重定向到的路由,我/error_page仅用于示例目的。您可以了解有关错误处理的更多信息'

Don't forget to import the ModelNotFoundException like this use Illuminate\Database\Eloquent\ModelNotFoundException;

不要忘记像这样导入 ModelNotFoundException use Illuminate\Database\Eloquent\ModelNotFoundException;

回答by Calvin

Adding on to the answer by Elias Soares, This happens because laravel generates an "Illuminate\Database\Eloquent\ModelNotFoundException" exception if firstOrFail don't return results.

添加 Elias Soares 的答案,这是因为如果 firstOrFail 不返回结果,laravel 会生成“Illuminate\Database\Eloquent\ModelNotFoundException”异常。

Reference: https://laravel.com/docs/5.8/eloquent#retrieving-single-models

参考:https: //laravel.com/docs/5.8/eloquent#retrieving-single-models

It's upto you how you want to handle this exception. If using firstOrFail -> to first() solution

您想如何处理此异常取决于您。如果使用 firstOrFail -> to first() 解决方案

After replacing firstOrFail with first, You would get the error: "Trying to get property of non object", That's because your query didn't fetched anything, so it won't have attribute. For that you can place a check on the results of your query.

用 first 替换 firstOrFail 后,您会收到错误:“试图获取非对象的属性”,这是因为您的查询未获取任何内容,因此它没有属性。为此,您可以检查查询结果。

$location = City::where('slug',$location_id)->where('status','1')->first();

!empty($location->attribute)?$location->attribute:null;

回答by Jodeveloper8

Replace this:

替换这个:

$location = City::where('slug',$location_id)->where('status','1')->firstOrFail();

With this:

有了这个:

$location = City::where('slug',$location_id)->where('status','1')->first();