Laravel Collections 计数结果

Laravel Collections counting result

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

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

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

但是当我这样做时:

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

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

如何检查是否找到了不止一条记录?


更新:

好的,多亏了大家,我现在看到了 collection 和模型之间的结果差异。

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

if(count($coll) > 1)

可行,但这是正确的方法吗?

您似乎在期待 find()-method to behave differently. From the docs

Find a model by its primary key.

以下是您那里的代码的情况:

1. 当调用 User::all() 时,你会得到一个 Illuminate\Database\Eloquent\Collection,你可以在上面调用 count 来计算像这样收集:

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

这将 return 集合中的项目数,正如您正确预期的那样。

2. 但是,当调用 User::find(2) 时,Eloquent 查询生成器不会 return 一个 Collection,因为它将检查有多少结果,因为你传递了 一个 ID,你最多会得到 一个结果,所以它会 return 改为 Eloquent 模型。该模型没有 count() 方法,因此当您尝试调用 $coll->count(); 时,它将转到 class 已实现的魔法 __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);
}

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

底线是第一个和第二个代码示例最终都做同样的事情:计算 users table 中的所有条目.

因为正如我在上面指出的那样,一个 ID 不能匹配超过一行(因为 ID 是唯一的),您问题的答案 是没有必要或计算 find(2) 结果的方法,因为它只能是 0(如果 null 是 returned)或 1(如果 Model 是 returned ).


更新

首先,为了将来参考,您可以使用PHP get_class to determine the class name of an object or get_parent_class 来确定它正在扩展的class。在您的情况下,第二个函数 get_parent_class 可能对确定模型 class 有用,因为 User class 扩展了 Laravel 抽象模型 class。

因此,如果您有模型,get_class($coll) 将报告 User,但 get_parent_class($coll) 将报告 \Illuminate\Database\Eloquent\Model

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

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

您的支票应如下所示:

// 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)

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

if (is_null($coll))

如果您的问题是检查它是否来自 collection。如果它来自 Illuminate\Database\Eloquent\Collection.

,你为什么不检查它
if (get_class($coll) == 'Illuminate\Database\Eloquent\Collection') {
   your code...
}

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