Illuminate \ Database \ Eloquent \ ModelNotFoundException - 模型中没有查询结果在laravel中

时间:2014-04-25 18:00:54

标签: php laravel laravel-4

我有以下数据模型

enter image description here

我想获得一个Servicio Auth_Token Tecnicoid Servicio,但我收到以下错误出现

enter image description here

这是我的代码

路线

Route::post('servicio/download/{id}', array('uses' => 'ServicioController@pdf'));

Servicio模型

class Servicio extends Eloquent{
protected $table  = 'Servicio';
protected $fillable = array(
                            'RutaFoto1',
                            'RutaFoto2',
                            'RutaFoto3',
                            'RutaFoto4',
                            'FechaTermino',
                            'Latitud',
                            'Longitud'
                            );
protected $primaryKey = 'idServicio';

public function materialUsado(){
    return $this->hasMany('Material_Usado', 'idMaterial_Usado');
}

public function tecnicos(){
    return $this->belongsToMany('Tecnico', 'Servicio_Tecnico', 'Servicio_idServicio', 'Tecnico_idTecnico');
}
    }

Tecnico模型

class Tecnico extends Eloquent{
protected $table = 'Tecnico';
protected $fillable = array('Auth_Token');
protected $primaryKey = 'idTecnico';

public function servicios(){
    return $this->belongsToMany('Servicio', 'Servicio_Tecnico', 'Tecnico_idTecnico', 'Servicio_idServicio');
}
 }

ServicioController

class ServicioController extends BaseController{

public function pdf($id){
    $auth = Input::get('Auth_Token');
    $tecnico = Tecnico::with('servicios')->where('Auth_Token',$auth)->firstOrFail();
        if($tecnico != ''){
            $servicios = $tecnico->servicios;
            $servicio = $servicio->where('idServicio', $id)->first();
            if($servicio != null){
                $array = array(
                            'idServicio' => $servicio->idServicio,
                            'RutaPDF' => base64_encode($servicio->RutaPDF),
                                );
                $response = Response::json($$array);
                return $response;
            }else{
                $array = array('Error' => '', 'Code' => '');
                return Response::json($array);
            }
        }else{
            $array = array('Error' => 'NotAuthorizedError', 'Code' => '403', 'Message' => 'Tecnico inexistente');
            $response = Response::json($array);
            return $response;
        }

}
    } 

我该如何解决?

1 个答案:

答案 0 :(得分:2)

你正在使用这个:

$tecnico = Tecnico::with('servicios')->where('Auth_Token',$auth)->firstOrFail();

在这种情况下,如果firstOrFail找不到请求的模型,则Illuminate\Database\Eloquent\ModelNotFoundException会抛出Auth_Token异常,因此可能是因为具有该Auth_Token字段的模型不可用。

确保Auth_Token正确且数据库中dd(Input::get('Auth_Token'))可用。您可以尝试POST检查您从用户提交的{{1}}收到的内容。