雄辩 ->first() if ->exists()

2022-08-30 08:18:03

我想获取表中条件匹配的第一行:

User::where('mobile', Input::get('mobile'))->first()

它运行良好,但如果条件不匹配,则会引发异常:

ErrorException
Trying to get property of non-object

目前我是这样解决的:

if (User::where('mobile', Input::get('mobile'))->exists()) {
    $user = User::where('mobile', Input::get('mobile'))->first()
}

我可以在不运行两个查询的情况下执行此操作吗?


答案 1

注意:first() 方法不会像原始问题中描述的那样引发异常。如果遇到此类异常,则代码中存在另一个错误。

用户 first() 并检查结果的正确方法:

$user = User::where('mobile', Input::get('mobile'))->first(); // model or null
if (!$user) {
   // Do stuff if it doesn't exist.
}

其他技术(不推荐,不必要的开销):

$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();
}

每种方法都是获得所需结果的不同方法。


答案 2

(ps - 我无法评论)我认为你最好的选择是像你做过的事情,或者类似于:

$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();

哦,还有:相反,如果但这可以在之后使用。count()existsget


推荐