php Laravel Collections 计数结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30178809/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:36:11  来源:igfitidea点击:

Laravel Collections counting result

phplaravelcollections

提问by Klaaz

On a User model (table with 4 records), when I do:

在用户模型(有 4 条记录的表)上,当我这样做时:

$coll = User::all();
echo $coll->count();

I get the amount of records found (4).

我得到了找到的记录数量 (4)。

But when I do:

但是当我这样做时:

$coll = User::find(2);
echo $coll->count();

I do not get 1 (As I expect) but the amount of attributes in the resulting collection (23 in this case).

我没有得到 1(如我所料),而是结果集合中的属性数量(在本例中为 23)。

How can I check if more then one records are found?

如何检查是否找到了多条记录?



UPDATE:

更新:

OK, thanks to you all I now see the difference in result between collection and model.

好的,多亏了你们,我现在看到了集合和模型之间的结果差异。

But my real problem is that I have to detect if I am having a model or a collection as a result. Depending on this result I perform some changes on the contents of the fields in the items (with map()) or model. How can I detect if the result is a model or a collection?

但我真正的问题是我必须检测结果是我有一个模型还是一个集合。根据此结果,我对项目(使用 map())或模型中的字段内容进行了一些更改。如何检测结果是模型还是集合?

if(count($coll) > 1)

Works, but is this the right approach?

有效,但这是正确的方法吗?

回答by Bogdan

Here's what's going on with the code you have there:

这是您在那里拥有的代码的情况:

1.When calling User::all()you'll get a Illuminate\Database\Eloquent\Collectionon which you can call countwhich counts the elements in the collection like so:

1.调用时User::all()你会得到一个Illuminate\Database\Eloquent\Collection你可以调用的count,它对集合中的元素进行计数,如下所示:

public function count()
{
    return count($this->items);
}

This will return the number of items in the collection as you correctly expected.

这将按照您的预期返回集合中的项目数。

2.When calling User::find(2)however, the Eloquent Query Builder will not return a Collection, because it will check to see how many results there are, and since you passed one IDyou'll get at most one result, so it will return an Eloquent Model instead. The Model does not have a count()method, so when you try to call $coll->count();it will go to the magic __callmethod that the class has implemented which looks like this:

2.User::find(2)但是,当调用时,Eloquent Query Builder 不会返回 a Collection,因为它会检查有多少结果,并且由于您传递了一个 ID,因此您最多只能得到一个 result,因此它将返回一个 Eloquent 模型. Model 没有count()方法,因此当您尝试调用$coll->count();它时,将转到__call该类已实现的魔术方法,如下所示:

public function __call($method, $parameters)
{
    if (in_array($method, array('increment', 'decrement')))
    {
        return call_user_func_array(array($this, $method), $parameters);
    }

    $query = $this->newQuery();

    return call_user_func_array(array($query, $method), $parameters);
}

As you can see the method tries to see if it should call a couple of hardcoded methods (incrementand decrement), which of course don't match in this case because $method = 'count', so it continues to create a new Query on which it will call the countmethod.

正如您所看到的,该方法试图查看它是否应该调用几个硬编码方法(incrementdecrement),在这种情况下这当然不匹配,因为$method = 'count',因此它继续创建一个新的查询,它将在其上调用该count方法。

The bottom line is that both the first and second code samples end up doing the same thing: counting all the entries in the userstable.

最重要的是,第一个和第二个代码示例最终都在做同样的事情:计算userstable中的所有条目

And since, as I pointed our above, one ID cannot match more than one row (since IDs are unique), the answer to your questionis that there's no need or way to count the results of find(2), since it can only be 0 (if nullis returned) or 1 (if a Modelis returned).

而且,正如我在上面指出的,一个 ID 不能匹配多于一行(因为 ID 是唯一的),因此您的问题答案是没有必要或方法来计算 的结果find(2),因为它只能是 0(如果null返回)或 1(如果Model返回 a)。



UPDATE

更新

First of all, for future reference you can use the PHP get_classto determine the class name of an object or get_parent_classto determine the class it is extending. In your case the second function get_parent_classmight be useful for determining the model class since the Userclass extends a Laravel abstract Model class.

首先,为了将来参考,您可以使用 PHPget_class来确定对象的类名或get_parent_class确定它正在扩展的类。在您的情况下,第二个函数get_parent_class可能对确定模型类很有用,因为User该类扩展了 Laravel 抽象模型类。

So if you have a model get_class($coll)will report User, but get_parent_class($coll)will report \Illuminate\Database\Eloquent\Model.

所以如果你有模型get_class($coll)会报User,但get_parent_class($coll)会报\Illuminate\Database\Eloquent\Model

Now to check if the result is a Collection or a Model you can use instanceof:

现在检查结果是集合还是模型,您可以使用instanceof

instanceofis used to determine whether a PHP variable is an instantiated object of a certain class

instanceof用于判断一个PHP变量是否是某个类的实例化对象

Your checks should look something like this:

您的支票应如下所示:

// Check if it's a Collection
if ($coll instanceof \Illuminate\Support\Collection)

// Check if it's a Model
if ($coll instanceof \Illuminate\Database\Eloquent\Model)

You might also want to check if the result is null, since findwill return nullif no entry is found with the given ID:

您可能还想检查结果是否为null,因为如果没有找到具有给定 ID 的条目,find它将返回null

if (is_null($coll))

回答by sevenforce

It seems you are expecting the find()-methodto behave differently. From the docs

您似乎希望find() 方法的行为有所不同。从文档

Find a model by its primary key.

回答by Rowell Dinglasa

If you problem is by checking if its from collection. Why don't you check it if its from Illuminate\Database\Eloquent\Collection.

如果你的问题是通过检查它是否来自集合。你为什么不检查它是否来自 Illuminate\Database\Eloquent\Collection。

if (get_class($coll) == 'Illuminate\Database\Eloquent\Collection') {
   your code...
}

or

或者

if ($coll instanceof \Illuminate\Database\Eloquent\Collection) {
   your code...
}