Laravel 查询\Builder中的findOrFail()
返回 调用undefined method\Database\Query\Builder::findOrFail() 我不想在这里使用模型 实现这一目标的最佳方式是什么?(当id不在表中时,我只想返回一个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 然后在该点中止
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
}