laravel Eloquent Collection:计数和检测空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20563166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Eloquent Collection: Counting and Detect Empty
提问by bitinn
This may be a trivial question but I am wondering if Laravel recommends a certain way to check whether an Eloquent collection returned from $result = Model::where(...)->get()
is empty, as well as counting the number of elements.
这可能是一个微不足道的问题,但我想知道 Laravel 是否推荐某种方法来检查从返回的 Eloquent 集合是否$result = Model::where(...)->get()
为空,以及计算元素的数量。
We are currently using !$result
to detect empty result, is that sufficient? As for count($result)
, does it actually cover all cases, including empty result?
我们目前正在使用!$result
检测空结果,这是否足够?至于count($result)
,它是否真的涵盖了所有情况,包括空结果?
回答by Gary Green
When using ->get()
you cannot simply use any of the below:
使用->get()
时不能简单地使用以下任何一种:
if (empty($result)) { }
if (!$result) { }
if ($result) { }
Because if you dd($result);
you'll notice an instance of Illuminate\Support\Collection
is always returned, even when there are no results. Essentially what you're checking is $a = new stdClass; if ($a) { ... }
which will always return true.
因为如果您dd($result);
会注意到Illuminate\Support\Collection
始终返回一个实例,即使没有结果也是如此。本质上,您正在检查的$a = new stdClass; if ($a) { ... }
内容将始终返回 true。
To determine if there are any results you can do any of the following:
要确定是否有任何结果,您可以执行以下任一操作:
if ($result->first()) { }
if (!$result->isEmpty()) { }
if ($result->count()) { }
if (count($result)) { }
You could also use ->first()
instead of ->get()
on the query builder which will return an instance of the first found model, or null
otherwise. This is useful if you need or are expecting only one result from the database.
您还可以在查询构建器上使用->first()
而不是,->get()
它会返回第一个找到的模型的实例,或者null
以其他方式。如果您只需要或期望来自数据库的一个结果,这将非常有用。
$result = Model::where(...)->first();
if ($result) { ... }
Notes / References
注释/参考
->first()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_firstisEmpty()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty->count()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_countcount($result)
works because the Collection implements Countableand an internalcount()
method: http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count
->first()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_firstisEmpty()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_isEmpty->count()
http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_countcount($result)
之所以有效,是因为 Collection 实现了Countable和一个内部count()
方法:http: //laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_count
Bonus Information
奖金信息
The Collection and the Query Builder differences can be a bit confusing to newcomers of Laravel because the method names are often the same between the two. For that reason it can be confusing to know what one you're working on. The Query Builder essentially builds a query until you call a method where it will execute the query and hit the database (e.g. when you call certain methods like ->all()
->first()
->lists()
and others). Those methods alsoexist on the Collection
object, which can get returned from the Query Builder if there are multiple results. If you're not sure what class you're actually working with, try doing var_dump(User::all())
and experimenting to see what classes it's actually returning (with help of get_class(...)
). I highly recommend you check out the source code for the Collection class, it's pretty simple. Then check out the Query Builder and see the similarities in function names and find out when it actually hits the database.
Collection 和 Query Builder 的差异对于 Laravel 的新手来说可能有点令人困惑,因为两者的方法名称通常相同。出于这个原因,知道你在做什么可能会令人困惑。查询生成器本质上构建一个查询,直到您调用一个方法,在该方法中它将执行查询并访问数据库(例如,当您调用某些方法时->all()
->first()
->lists()
)。这些方法也存在于Collection
对象上,如果有多个结果,可以从查询生成器返回。如果您不确定您实际使用的是哪个类,请尝试执行var_dump(User::all())
并试验以查看它实际返回的类(在get_class(...)
)。我强烈建议您查看 Collection 类的源代码,它非常简单。然后查看查询生成器并查看函数名称的相似之处,并找出它实际访问数据库的时间。
回答by clod986
I think you are looking for:
我认为您正在寻找:
$result->isEmpty()
This is different from empty($result)
, which will not be true because the result will be an empty collection. Your suggestion of count($result)
is also a good solution. I cannot find any reference in the docs
这与 不同empty($result)
,后者不会为真,因为结果将是一个空集合。您的建议count($result)
也是一个很好的解决方案。我在文档中找不到任何参考
回答by sathish R
I agree the above approved answer. But usually I use $results->isNotEmpty()
method as given below.
我同意上述批准的答案。但通常我使用$results->isNotEmpty()
下面给出的方法。
if($results->isNotEmpty())
{
//do something
}
It's more verbose than if(!results->isEmpty())
because sometimes we forget to add '!' in front which may result in unwanted error.
它比if(!results->isEmpty())
因为有时我们忘记添加 '!'更冗长。在前面,这可能会导致不必要的错误。
Note that this method exists from version 5.3onwards.
请注意,此方法从5.3版本开始存在。
回答by Lovepreet Singh
There are several methods given in Laravel for checking results count/check empty/not empty:
Laravel 中给出了几种方法来检查结果计数/检查空/非空:
$result->isNotEmpty(); // True if result is not empty.
$result->isEmpty(); // True if result is empty.
$result->count(); // Return count of records in result.
回答by Jignesh Joisar
I think better to used
我认为更好地使用
$result->isEmpty();
The isEmpty method returns true if the collection is empty; otherwise, false is returned.
如果集合为空,则 isEmpty 方法返回 true;否则,返回 false。
回答by pardeep
I think you try something like
我想你尝试像
@if(!$result->isEmpty())
// $result is not empty
@else
// $result is empty
@endif
or also use
或也使用
if (!$result) { }
if ($result) { }
回答by Patrick Lumenus
You can do
你可以做
$result = Model::where(...)->count();
to count the results.
来计算结果。
You can also use
你也可以使用
if ($result->isEmpty()){}
to check whether or not the result is empty.
检查结果是否为空。
回答by Udhav Sarvaiya
According to Laravel Documentationstates you can use this way:
根据 Laravel文档说明,您可以使用这种方式:
$result->isEmpty();
The isEmpty
method returns true
if the collection is empty; otherwise, false
is returned.
如果集合为空,则该isEmpty
方法返回true
;否则,false
返回。
回答by nazmulhaqued
You can use:$counter = count($datas);
您可以使用:$counter = count($datas);
回答by Ravindra Bhanderi
------SOLVED------
- - - 解决了 - - -
in this case you want to check two type of count for two cace
在这种情况下,您要检查两个 cace 的两种类型的计数
case 1:
情况1:
if result contain only one record other word select single row from database using ->first()
如果结果仅包含一条记录,则使用 ->first() 从数据库中选择单行
if(count($result)){
...record is exist true...
}
case 2:
案例2:
if result contain set of multiple row other word using ->get() or ->all()
如果结果包含多行其他词的集合,则使用 ->get() 或 ->all()
if($result->count()) {
...record is exist true...
}