Query\Builder 中的 findOrFail()
findOrFail() in Query\Builder
DB::table('amounts')->findOrFail($id);
return
Call to undefined method Illuminate\Database\Query\Builder::findOrFail()
我不想在这里使用模型。
实现此目标的最佳方法是什么? (我只想return一个404
当id不在table的时候。)
同时我做:
$amount = DB::table('amounts')->find($request->input('amount'));
if(!$amount) abort(404);
如果您不想使用模型,那也行。如果您使用模型,您可以 try
和 catch
\Illuminate\Database\Eloquent\ModelNotFoundException
并在那时中止 404
。
您可以尝试使用以下代码获取记录是否退出 table:
$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
}
希望对您有所帮助。
如您在此 API 文档中所见
https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_find
https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_findOrFail
find($id)
是 Database Builder 方法,但 findOrFail($id)
不是,因此您不能直接使用它。
我真的不明白为什么你不想使用 Eloquent 模型 但这是做或坚持你正在做的事情的好方法与此同时。
DB::table('amounts')->findOrFail($id);
return
Call to undefined method Illuminate\Database\Query\Builder::findOrFail()
我不想在这里使用模型。
实现此目标的最佳方法是什么? (我只想return一个404
当id不在table的时候。)
同时我做:
$amount = DB::table('amounts')->find($request->input('amount'));
if(!$amount) abort(404);
如果您不想使用模型,那也行。如果您使用模型,您可以 try
和 catch
\Illuminate\Database\Eloquent\ModelNotFoundException
并在那时中止 404
。
您可以尝试使用以下代码获取记录是否退出 table:
$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
}
希望对您有所帮助。
如您在此 API 文档中所见
https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_find
https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_findOrFail
find($id)
是 Database Builder 方法,但 findOrFail($id)
不是,因此您不能直接使用它。
我真的不明白为什么你不想使用 Eloquent 模型 但这是做或坚持你正在做的事情的好方法与此同时。