![](/img/trans.png)
[英]What is the best way to apply query strings in eloquent where statements?
[英]What is the best way to check if an Eloquent query returns no answer?
我正在使用Laravel 4.說我有一個雄辯的模型(患者),我想找一個名叫Bob的病人,我會這樣做:
$patient = Patient::where('name', '=', 'Bob');
檢查$ patient是否為有效記錄的最佳方法是什么?
如果數據庫查詢未找到任何匹配結果,則返回null
。 因此...
$patient = Patient::where('name','=','Bob')->first();
if ( is_null($patient) ) {
App::abort(404);
}
(注意:在您的原始問題中,您在查詢中忘記了->first()
(或->get()
)。不要忘記,否則您將得到一個Eloquent對象而不是結果。)
用這個:
$patient = Patient::where('name', '=', 'Bob')->firstOrFail();
它會在成功時返回Eulqouent模型,或者在失敗時拋出ModelNotFoundException。
我知道這已經過時了,但是隨着第二次谷歌搜索,這就出現了。 。 。 對於你不期望一個記錄或不能使用的情況->firstOrFail()
(我的用例是一個async typeahead api,最多返回10個結果),對我來說唯一有效的是count():
$patient = Patient::where('name', '=', 'Bob')->get(); //you could have more than one bob
if (!count($patient)) {
return 'No records found';
}
$patient = Patient::where('name','Bob')->get();
if ( $patient->isEmpty() ) {
return response(['error' => 'Record not found'], 404);
}
像Patient::where('name', '=', 'Bob')->exists()
可能會起作用。 它將返回一個布爾值。
只需使用本機php中的empty()
將解決所有問題,如果對象為null則返回true,如果laravel的查詢構建器collection
為空(但已初始化),它也將返回true。
$contributor = Contributor::whereVendor('web')->first();
if(empty($contributor)){
...
}
如果您正在傳遞id
參數以獲取單個記錄,請使用findOrFail($id)
我在尋找解決方案的同時找到了這個::find($id)->firstOrFail
語法,它是錯誤的。
$patient = Patient::findOrFail($id);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.