提问者:小点点

雄辩->第一个()如果->存在()


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

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

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


共3个答案

匿名用户

注意: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();
}

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

匿名用户

(ps-我无法置评)我认为你最好的选择是像你所做的那样,或者类似于:

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

哦,还有:如果存在,则改为count(),但这可能是在get之后使用的东西。

匿名用户

get返回Collection,并且应该获取多行。

count是检查结果的通用方法:

$user = User::where(...)->first(); // returns Model or null
if (count($user)) // do what you want with $user

// or use this:
$user = User::where(...)->firstOrFail(); // returns Model or throws ModelNotFoundException

// count will works with a collection of course:
$users = User::where(...)->get(); // returns Collection always (might be empty)
if (count($users)) // do what you want with $users