你可以打电话Builder
在 Eloquent 模型上运行,因为Model
类使用魔法__call
方法。
正如您在下面的方法定义中看到的,如果该方法在类中不存在,或者不存在increment
or decrement
, a new Builder
创建查询,并在该查询上调用该方法。
public function __call($method, $parameters)
{
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
try {
return $this->newQuery()->$method(...$parameters);
} catch (BadMethodCallException $e) {
throw new BadMethodCallException(
sprintf('Call to undefined method %s::%s()', get_class($this), $method)
);
}
}
https://github.com/Illuminate/database/blob/master/Eloquent/Model.php#L1439 https://github.com/illuminate/database/blob/master/Eloquent/Model.php#L1439
至于a之间的区别Model
, Builder
and Collection
:
Model
:这遵循模型本质上是数据库行的实例的模式,允许您创建、更新和删除单个行。
Builder
:这是应用程序和数据库之间的抽象层。通常,它用于为您提供通用 API 来构建与平台无关的数据库查询。例如。他们将在 MySQL、Postgres、SQL Server 等上工作。
Collection
: 这基本上是一个array
使用类固醇。它为标准提供了可链接的APIarray_*
类型 PHP 函数,以及其他用于操作数据集合的有用函数。