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 查看是否应该调用两个硬编码的方法(increment
和decrement
),这两个方法在本例中当然不匹配,因为是$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))