本文介绍了雄辩 - > first()if - > exists()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

效果很好,但如果条件不匹配,它会抛出异常:

  ErrorException 
尝试获取非对象的属性

目前我解决了这个问题:



<$ p如果(User :: where('mobile',Input :: get('mobile')) - > exists()){
$ user = User :: where( 'mobile',Input :: get('mobile')) - > first()
}

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

解决方案

注意:first()会抛出原始问题中所述的异常。如果您遇到这种异常,您的代码中会出现另一个错误。



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

  $ user = User :: where('mobile',Input :: get('mobile')) - >第一(); // model或null 
if(!$ user){
//如果不存在,请执行该操作。
}

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

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

if(!$ user-> isEmpty()){
$ firstUser = $ user-> first()
}

  try {
$ user = User :: where('mobile',Input :: get('mobile')) - > firstOrFail();
//当用户存在时进行填充。
} catch(ErrorException $ e){
//如果不存在,请进行填充。
}

  //使用下列任一项。 
$ users = User :: where('mobile',Input :: get('mobile')) - > get(); // Collection

if(count($ users)){
//使用集合,获取第一个项目使用$ users-> first()。
//如果您使用 - > first();请使用该模型。
}

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


I want to get the first row in table where condition matches:

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

It works well, but if the condition doesn't match, it throws an Exception:

ErrorException
Trying to get property of non-object

Currently I resolve it like this:

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

Can I do this without running two queries?

解决方案

Note: The first() method doesn't throw an exception as described in the original question. If you're getting this kind of exception, there is another error in your code.

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.
}

Other techniques (not recommended, unnecessary overhead):

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

if (!$user->isEmpty()){
    $firstUser = $user->first()
}

or

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

or

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

Each one is a different way to get your required result.

这篇关于雄辩 - &gt; first()if - &gt; exists()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 13:17