本文介紹了Eloquent ->first() 如果 ->exists()的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我想獲取條件匹配的表中的第一行:
I want to get the first row in table where condition matches:
User::where('mobile', Input::get('mobile'))->first()
效果很好,但如果條件不匹配,則會(huì)拋出異常:
It works well, but if the condition doesn't match, it throws an Exception:
ErrorException
Trying to get property of non-object
目前我是這樣解決的:
if (User::where('mobile', Input::get('mobile'))->exists()) {
$user = User::where('mobile', Input::get('mobile'))->first()
}
我可以在不運(yùn)行兩個(gè)查詢的情況下執(zhí)行此操作嗎?
Can I do this without running two queries?
推薦答案
注意:first() 方法不會(huì)像原始問題中描述的那樣拋出異常.如果您收到此類異常,則說明您的代碼中存在另一個(gè)錯(cuò)誤.
使用 first() 并檢查結(jié)果的正確方法:
The correct way to user first() and check for a result:
$user = User::where('mobile', Input::get('mobile'))->first(); // model or null
if (!$user) {
// Do stuff if it doesn't exist.
}
其他技術(shù)(不推薦,不必要的開銷):
Other techniques (not recommended, unnecessary overhead):
$user = User::where('mobile', Input::get('mobile'))->get();
if (!$user->isEmpty()){
$firstUser = $user->first()
}
或
try {
$user = User::where('mobile', Input::get('mobile'))->firstOrFail();
// Do stuff when user exists.
} catch (ErrorException $e) {
// Do stuff if it doesn't exist.
}
或
// Use either one of the below.
$users = User::where('mobile', Input::get('mobile'))->get(); //Collection
if (count($users)){
// Use the collection, to get the first item use $users->first().
// Use the model if you used ->first();
}
每種方法都是獲得所需結(jié)果的不同方式.
Each one is a different way to get your required result.
這篇關(guān)于Eloquent ->first() 如果 ->exists()的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!