在用户模型(包含4条记录的表)上,当我执行以下操作时:

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

I get the amount of records found (4).

But when I do:

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

我得到的不是1(正如我所期望的),而是结果集合中的属性数量(在本例中为23).

如何判断是否找到多个记录?


UPDATE:

好的,多亏了你们,我现在看到了收集和模型之间的差异.

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?

if(count($coll) > 1)

Works, but is this the right approach?

推荐答案

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

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

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

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

2.然而,当调用User::find(2)时,Eloquent 的查询生成器不会返回Collection,因为它会判断有多少个结果,并且因为你通过了one ID,你最多会得到one result个,所以它会返回Eloquent 的模型.该模型没有count()方法,因此当您try 调用$coll->count();时,它将转到该类已实现的magic __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);
}

正如您所见,该方法try 查看是否应该调用两个硬编码的方法(incrementdecrement),这两个方法在本例中当然不匹配,因为是$method = 'count',所以它会继续创建一个新的查询,并对其调用count方法.

底线是,第一个和第二个代码示例最终都做了同样的事情:counting all the entries in the 100 table.

正如我在上面指出的,由于一个ID不能匹配多个行(因为ID是唯一的),answer to your question表示没有必要也没有方法计算find(2)的结果,因为它只能是0(如果返回null)或1(如果返回Model).


UPDATE

首先,为了便于将来参考,您可以使用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.

现在要判断结果是集合还是模型,可以使用instanceof:

instanceof用于确定PHP变量是否是某个类的实例化对象

你的支票应该是这样的:

// 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 find will return null if no entry is found with the given ID:

if (is_null($coll))

Laravel相关问答推荐

如何使用 Laravel 进行继承

在 Laravel 中排序的集合在 Vue 中突然不再排序

在 React 中将属性从一个组件传递到另一个组件

如何将用户对象绑定到中间件中的请求

Laravel 5.7 判断Electron邮件是否经过验证

Twilio 查找 API 不起作用?

Homestead:文件夹映射到错误的文档根目录

如何更改 ember-cli 中的 dist 文件夹路径?

使用 laravel eloquent 关系检索除 NULL 之外的所有记录

在 laravel 分页中添加一些数据

Laravel 控制器构造

Laravel 5:在同一字符串上使用 bcrypt 给出不同的值

PHP Laravel:如何获取客户端浏览器/设备?

WhereHas Laravel 中的关系计数条件是什么

如何在 Laravel Mix 中将公共路径更改为包含下划线的内容?

Laravel 分页漂亮的 URL

使用 Queue::fake() 测试监听器

[Vue 警告]:找不到元素:#app

Laravel 5 默认注册后如何发送邮件?

Laravel 5 new auth:获取当前用户以及如何实现角色?