问题描述
我想得到条件匹配的表格中的第一行:
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.
这篇关于雄辩 - > first()if - > exists()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!