Eloquent - > first()if - > exists()

Web*_*nan 51 php laravel eloquent

我想得到条件匹配的表中的第一行:

User::where('mobile', Input::get('mobile'))->first()
Run Code Online (Sandbox Code Playgroud)

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

ErrorException
Trying to get property of non-object
Run Code Online (Sandbox Code Playgroud)

目前我这样解决:

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

我可以不运行两个查询吗?

Mat*_*row 114

注意:first()方法不会抛出原始问题中描述的异常.如果您遇到此类异常,则代码中会出现另一个错误.

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

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

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

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

if (!$user->isEmpty()){
    $firstUser = $user->first()
}
Run Code Online (Sandbox Code Playgroud)

要么

try {
    $user = User::where('mobile', Input::get('mobile'))->firstOrFail();
    // Do stuff when user exists.
} catch (ErrorException $e) {
    // Do stuff if it doesn't exist.
}
Run Code Online (Sandbox Code Playgroud)

要么

// 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();
}
Run Code Online (Sandbox Code Playgroud)

每一种都是获得所需结果的不同方式.

  • @dangel No first() 不会返回一个集合,这将返回初始集合中的第一个模型对象,如果有的话。 (2认同)