Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 查询\Builder中的findOrFail()_Laravel_Laravel 5_Query Builder - Fatal编程技术网

Laravel 查询\Builder中的findOrFail()

Laravel 查询\Builder中的findOrFail(),laravel,laravel-5,query-builder,Laravel,Laravel 5,Query Builder,返回 调用undefined method\Database\Query\Builder::findOrFail() 我不想在这里使用模型 实现这一目标的最佳方式是什么?(当id不在表中时,我只想返回一个404。) 与此同时,我确实: DB::table('amounts')->findOrFail($id); 如果你不想使用模型,那就可以了。如果使用型号,您可以尝试和捕获 \Illumb\Database\Eloquent\ModelNotFoundException 然后在该点中止

返回

调用undefined method\Database\Query\Builder::findOrFail()

我不想在这里使用模型

实现这一目标的最佳方式是什么?(当id不在表中时,我只想返回一个
404
。)


与此同时,我确实:

DB::table('amounts')->findOrFail($id);

如果你不想使用模型,那就可以了。如果使用型号,您可以
尝试
捕获

\Illumb\Database\Eloquent\ModelNotFoundException


然后在该点中止
404

若退出到表中或未退出,您可以尝试使用以下代码获取记录:

$amount = DB::table('amounts')->find($request->input('amount'));
if(!$amount) abort(404);

希望这有帮助。

正如您在本API文档中看到的那样

find($id)
Database Builder方法,但
findOrFail($id)
不是,因此不能直接使用它


我真的不明白你为什么不想使用有说服力的模型,但这是一个很好的方法来做或坚持你正在做的事情。

如果你不想使用模型,你的第二个变体是正常的。你知道findOrFail没有实现的原因吗?我想,因为查询生成器只是sql语言的包装器。雄辩模型是查询生成器和某些逻辑的组合。
$result = DB::table('amounts')->find($id);

if($result == NULL) //check if no record found
{
        //do your stuff here
}
else //if record found from table
{
        //do your stuff here
}