You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Builder.php 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. <?php
  2. namespace Illuminate\Database\Eloquent;
  3. use Closure;
  4. use Exception;
  5. use BadMethodCallException;
  6. use Illuminate\Support\Arr;
  7. use Illuminate\Support\Str;
  8. use Illuminate\Pagination\Paginator;
  9. use Illuminate\Contracts\Support\Arrayable;
  10. use Illuminate\Support\Traits\ForwardsCalls;
  11. use Illuminate\Database\Concerns\BuildsQueries;
  12. use Illuminate\Database\Eloquent\Relations\Relation;
  13. use Illuminate\Database\Query\Builder as QueryBuilder;
  14. /**
  15. * @property-read HigherOrderBuilderProxy $orWhere
  16. *
  17. * @mixin \Illuminate\Database\Query\Builder
  18. */
  19. class Builder
  20. {
  21. use BuildsQueries, Concerns\QueriesRelationships, ForwardsCalls;
  22. /**
  23. * The base query builder instance.
  24. *
  25. * @var \Illuminate\Database\Query\Builder
  26. */
  27. protected $query;
  28. /**
  29. * The model being queried.
  30. *
  31. * @var \Illuminate\Database\Eloquent\Model
  32. */
  33. protected $model;
  34. /**
  35. * The relationships that should be eager loaded.
  36. *
  37. * @var array
  38. */
  39. protected $eagerLoad = [];
  40. /**
  41. * All of the globally registered builder macros.
  42. *
  43. * @var array
  44. */
  45. protected static $macros = [];
  46. /**
  47. * All of the locally registered builder macros.
  48. *
  49. * @var array
  50. */
  51. protected $localMacros = [];
  52. /**
  53. * A replacement for the typical delete function.
  54. *
  55. * @var \Closure
  56. */
  57. protected $onDelete;
  58. /**
  59. * The methods that should be returned from query builder.
  60. *
  61. * @var array
  62. */
  63. protected $passthru = [
  64. 'insert', 'insertGetId', 'getBindings', 'toSql',
  65. 'exists', 'doesntExist', 'count', 'min', 'max', 'avg', 'average', 'sum', 'getConnection',
  66. ];
  67. /**
  68. * Applied global scopes.
  69. *
  70. * @var array
  71. */
  72. protected $scopes = [];
  73. /**
  74. * Removed global scopes.
  75. *
  76. * @var array
  77. */
  78. protected $removedScopes = [];
  79. /**
  80. * Create a new Eloquent query builder instance.
  81. *
  82. * @param \Illuminate\Database\Query\Builder $query
  83. * @return void
  84. */
  85. public function __construct(QueryBuilder $query)
  86. {
  87. $this->query = $query;
  88. }
  89. /**
  90. * Create and return an un-saved model instance.
  91. *
  92. * @param array $attributes
  93. * @return \Illuminate\Database\Eloquent\Model
  94. */
  95. public function make(array $attributes = [])
  96. {
  97. return $this->newModelInstance($attributes);
  98. }
  99. /**
  100. * Register a new global scope.
  101. *
  102. * @param string $identifier
  103. * @param \Illuminate\Database\Eloquent\Scope|\Closure $scope
  104. * @return $this
  105. */
  106. public function withGlobalScope($identifier, $scope)
  107. {
  108. $this->scopes[$identifier] = $scope;
  109. if (method_exists($scope, 'extend')) {
  110. $scope->extend($this);
  111. }
  112. return $this;
  113. }
  114. /**
  115. * Remove a registered global scope.
  116. *
  117. * @param \Illuminate\Database\Eloquent\Scope|string $scope
  118. * @return $this
  119. */
  120. public function withoutGlobalScope($scope)
  121. {
  122. if (! is_string($scope)) {
  123. $scope = get_class($scope);
  124. }
  125. unset($this->scopes[$scope]);
  126. $this->removedScopes[] = $scope;
  127. return $this;
  128. }
  129. /**
  130. * Remove all or passed registered global scopes.
  131. *
  132. * @param array|null $scopes
  133. * @return $this
  134. */
  135. public function withoutGlobalScopes(array $scopes = null)
  136. {
  137. if (! is_array($scopes)) {
  138. $scopes = array_keys($this->scopes);
  139. }
  140. foreach ($scopes as $scope) {
  141. $this->withoutGlobalScope($scope);
  142. }
  143. return $this;
  144. }
  145. /**
  146. * Get an array of global scopes that were removed from the query.
  147. *
  148. * @return array
  149. */
  150. public function removedScopes()
  151. {
  152. return $this->removedScopes;
  153. }
  154. /**
  155. * Add a where clause on the primary key to the query.
  156. *
  157. * @param mixed $id
  158. * @return $this
  159. */
  160. public function whereKey($id)
  161. {
  162. if (is_array($id) || $id instanceof Arrayable) {
  163. $this->query->whereIn($this->model->getQualifiedKeyName(), $id);
  164. return $this;
  165. }
  166. return $this->where($this->model->getQualifiedKeyName(), '=', $id);
  167. }
  168. /**
  169. * Add a where clause on the primary key to the query.
  170. *
  171. * @param mixed $id
  172. * @return $this
  173. */
  174. public function whereKeyNot($id)
  175. {
  176. if (is_array($id) || $id instanceof Arrayable) {
  177. $this->query->whereNotIn($this->model->getQualifiedKeyName(), $id);
  178. return $this;
  179. }
  180. return $this->where($this->model->getQualifiedKeyName(), '!=', $id);
  181. }
  182. /**
  183. * Add a basic where clause to the query.
  184. *
  185. * @param string|array|\Closure $column
  186. * @param mixed $operator
  187. * @param mixed $value
  188. * @param string $boolean
  189. * @return $this
  190. */
  191. public function where($column, $operator = null, $value = null, $boolean = 'and')
  192. {
  193. if ($column instanceof Closure) {
  194. $column($query = $this->model->newModelQuery());
  195. $this->query->addNestedWhereQuery($query->getQuery(), $boolean);
  196. } else {
  197. $this->query->where(...func_get_args());
  198. }
  199. return $this;
  200. }
  201. /**
  202. * Add an "or where" clause to the query.
  203. *
  204. * @param \Closure|array|string $column
  205. * @param mixed $operator
  206. * @param mixed $value
  207. * @return \Illuminate\Database\Eloquent\Builder|static
  208. */
  209. public function orWhere($column, $operator = null, $value = null)
  210. {
  211. [$value, $operator] = $this->query->prepareValueAndOperator(
  212. $value, $operator, func_num_args() === 2
  213. );
  214. return $this->where($column, $operator, $value, 'or');
  215. }
  216. /**
  217. * Add an "order by" clause for a timestamp to the query.
  218. *
  219. * @param string $column
  220. * @return $this
  221. */
  222. public function latest($column = null)
  223. {
  224. if (is_null($column)) {
  225. $column = $this->model->getCreatedAtColumn() ?? 'created_at';
  226. }
  227. $this->query->latest($column);
  228. return $this;
  229. }
  230. /**
  231. * Add an "order by" clause for a timestamp to the query.
  232. *
  233. * @param string $column
  234. * @return $this
  235. */
  236. public function oldest($column = null)
  237. {
  238. if (is_null($column)) {
  239. $column = $this->model->getCreatedAtColumn() ?? 'created_at';
  240. }
  241. $this->query->oldest($column);
  242. return $this;
  243. }
  244. /**
  245. * Create a collection of models from plain arrays.
  246. *
  247. * @param array $items
  248. * @return \Illuminate\Database\Eloquent\Collection
  249. */
  250. public function hydrate(array $items)
  251. {
  252. $instance = $this->newModelInstance();
  253. return $instance->newCollection(array_map(function ($item) use ($instance) {
  254. return $instance->newFromBuilder($item);
  255. }, $items));
  256. }
  257. /**
  258. * Create a collection of models from a raw query.
  259. *
  260. * @param string $query
  261. * @param array $bindings
  262. * @return \Illuminate\Database\Eloquent\Collection
  263. */
  264. public function fromQuery($query, $bindings = [])
  265. {
  266. return $this->hydrate(
  267. $this->query->getConnection()->select($query, $bindings)
  268. );
  269. }
  270. /**
  271. * Find a model by its primary key.
  272. *
  273. * @param mixed $id
  274. * @param array $columns
  275. * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
  276. */
  277. public function find($id, $columns = ['*'])
  278. {
  279. if (is_array($id) || $id instanceof Arrayable) {
  280. return $this->findMany($id, $columns);
  281. }
  282. return $this->whereKey($id)->first($columns);
  283. }
  284. /**
  285. * Find multiple models by their primary keys.
  286. *
  287. * @param \Illuminate\Contracts\Support\Arrayable|array $ids
  288. * @param array $columns
  289. * @return \Illuminate\Database\Eloquent\Collection
  290. */
  291. public function findMany($ids, $columns = ['*'])
  292. {
  293. if (empty($ids)) {
  294. return $this->model->newCollection();
  295. }
  296. return $this->whereKey($ids)->get($columns);
  297. }
  298. /**
  299. * Find a model by its primary key or throw an exception.
  300. *
  301. * @param mixed $id
  302. * @param array $columns
  303. * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static|static[]
  304. *
  305. * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
  306. */
  307. public function findOrFail($id, $columns = ['*'])
  308. {
  309. $result = $this->find($id, $columns);
  310. if (is_array($id)) {
  311. if (count($result) === count(array_unique($id))) {
  312. return $result;
  313. }
  314. } elseif (! is_null($result)) {
  315. return $result;
  316. }
  317. throw (new ModelNotFoundException)->setModel(
  318. get_class($this->model), $id
  319. );
  320. }
  321. /**
  322. * Find a model by its primary key or return fresh model instance.
  323. *
  324. * @param mixed $id
  325. * @param array $columns
  326. * @return \Illuminate\Database\Eloquent\Model|static
  327. */
  328. public function findOrNew($id, $columns = ['*'])
  329. {
  330. if (! is_null($model = $this->find($id, $columns))) {
  331. return $model;
  332. }
  333. return $this->newModelInstance();
  334. }
  335. /**
  336. * Get the first record matching the attributes or instantiate it.
  337. *
  338. * @param array $attributes
  339. * @param array $values
  340. * @return \Illuminate\Database\Eloquent\Model|static
  341. */
  342. public function firstOrNew(array $attributes, array $values = [])
  343. {
  344. if (! is_null($instance = $this->where($attributes)->first())) {
  345. return $instance;
  346. }
  347. return $this->newModelInstance($attributes + $values);
  348. }
  349. /**
  350. * Get the first record matching the attributes or create it.
  351. *
  352. * @param array $attributes
  353. * @param array $values
  354. * @return \Illuminate\Database\Eloquent\Model|static
  355. */
  356. public function firstOrCreate(array $attributes, array $values = [])
  357. {
  358. if (! is_null($instance = $this->where($attributes)->first())) {
  359. return $instance;
  360. }
  361. return tap($this->newModelInstance($attributes + $values), function ($instance) {
  362. $instance->save();
  363. });
  364. }
  365. /**
  366. * Create or update a record matching the attributes, and fill it with values.
  367. *
  368. * @param array $attributes
  369. * @param array $values
  370. * @return \Illuminate\Database\Eloquent\Model|static
  371. */
  372. public function updateOrCreate(array $attributes, array $values = [])
  373. {
  374. return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
  375. $instance->fill($values)->save();
  376. });
  377. }
  378. /**
  379. * Execute the query and get the first result or throw an exception.
  380. *
  381. * @param array $columns
  382. * @return \Illuminate\Database\Eloquent\Model|static
  383. *
  384. * @throws \Illuminate\Database\Eloquent\ModelNotFoundException
  385. */
  386. public function firstOrFail($columns = ['*'])
  387. {
  388. if (! is_null($model = $this->first($columns))) {
  389. return $model;
  390. }
  391. throw (new ModelNotFoundException)->setModel(get_class($this->model));
  392. }
  393. /**
  394. * Execute the query and get the first result or call a callback.
  395. *
  396. * @param \Closure|array $columns
  397. * @param \Closure|null $callback
  398. * @return \Illuminate\Database\Eloquent\Model|static|mixed
  399. */
  400. public function firstOr($columns = ['*'], Closure $callback = null)
  401. {
  402. if ($columns instanceof Closure) {
  403. $callback = $columns;
  404. $columns = ['*'];
  405. }
  406. if (! is_null($model = $this->first($columns))) {
  407. return $model;
  408. }
  409. return call_user_func($callback);
  410. }
  411. /**
  412. * Get a single column's value from the first result of a query.
  413. *
  414. * @param string $column
  415. * @return mixed
  416. */
  417. public function value($column)
  418. {
  419. if ($result = $this->first([$column])) {
  420. return $result->{$column};
  421. }
  422. }
  423. /**
  424. * Execute the query as a "select" statement.
  425. *
  426. * @param array $columns
  427. * @return \Illuminate\Database\Eloquent\Collection|static[]
  428. */
  429. public function get($columns = ['*'])
  430. {
  431. $builder = $this->applyScopes();
  432. // If we actually found models we will also eager load any relationships that
  433. // have been specified as needing to be eager loaded, which will solve the
  434. // n+1 query issue for the developers to avoid running a lot of queries.
  435. if (count($models = $builder->getModels($columns)) > 0) {
  436. $models = $builder->eagerLoadRelations($models);
  437. }
  438. return $builder->getModel()->newCollection($models);
  439. }
  440. /**
  441. * Get the hydrated models without eager loading.
  442. *
  443. * @param array $columns
  444. * @return \Illuminate\Database\Eloquent\Model[]|static[]
  445. */
  446. public function getModels($columns = ['*'])
  447. {
  448. return $this->model->hydrate(
  449. $this->query->get($columns)->all()
  450. )->all();
  451. }
  452. /**
  453. * Eager load the relationships for the models.
  454. *
  455. * @param array $models
  456. * @return array
  457. */
  458. public function eagerLoadRelations(array $models)
  459. {
  460. foreach ($this->eagerLoad as $name => $constraints) {
  461. // For nested eager loads we'll skip loading them here and they will be set as an
  462. // eager load on the query to retrieve the relation so that they will be eager
  463. // loaded on that query, because that is where they get hydrated as models.
  464. if (strpos($name, '.') === false) {
  465. $models = $this->eagerLoadRelation($models, $name, $constraints);
  466. }
  467. }
  468. return $models;
  469. }
  470. /**
  471. * Eagerly load the relationship on a set of models.
  472. *
  473. * @param array $models
  474. * @param string $name
  475. * @param \Closure $constraints
  476. * @return array
  477. */
  478. protected function eagerLoadRelation(array $models, $name, Closure $constraints)
  479. {
  480. // First we will "back up" the existing where conditions on the query so we can
  481. // add our eager constraints. Then we will merge the wheres that were on the
  482. // query back to it in order that any where conditions might be specified.
  483. $relation = $this->getRelation($name);
  484. $relation->addEagerConstraints($models);
  485. $constraints($relation);
  486. // Once we have the results, we just match those back up to their parent models
  487. // using the relationship instance. Then we just return the finished arrays
  488. // of models which have been eagerly hydrated and are readied for return.
  489. return $relation->match(
  490. $relation->initRelation($models, $name),
  491. $relation->getEager(), $name
  492. );
  493. }
  494. /**
  495. * Get the relation instance for the given relation name.
  496. *
  497. * @param string $name
  498. * @return \Illuminate\Database\Eloquent\Relations\Relation
  499. */
  500. public function getRelation($name)
  501. {
  502. // We want to run a relationship query without any constrains so that we will
  503. // not have to remove these where clauses manually which gets really hacky
  504. // and error prone. We don't want constraints because we add eager ones.
  505. $relation = Relation::noConstraints(function () use ($name) {
  506. try {
  507. return $this->getModel()->newInstance()->$name();
  508. } catch (BadMethodCallException $e) {
  509. throw RelationNotFoundException::make($this->getModel(), $name);
  510. }
  511. });
  512. $nested = $this->relationsNestedUnder($name);
  513. // If there are nested relationships set on the query, we will put those onto
  514. // the query instances so that they can be handled after this relationship
  515. // is loaded. In this way they will all trickle down as they are loaded.
  516. if (count($nested) > 0) {
  517. $relation->getQuery()->with($nested);
  518. }
  519. return $relation;
  520. }
  521. /**
  522. * Get the deeply nested relations for a given top-level relation.
  523. *
  524. * @param string $relation
  525. * @return array
  526. */
  527. protected function relationsNestedUnder($relation)
  528. {
  529. $nested = [];
  530. // We are basically looking for any relationships that are nested deeper than
  531. // the given top-level relationship. We will just check for any relations
  532. // that start with the given top relations and adds them to our arrays.
  533. foreach ($this->eagerLoad as $name => $constraints) {
  534. if ($this->isNestedUnder($relation, $name)) {
  535. $nested[substr($name, strlen($relation.'.'))] = $constraints;
  536. }
  537. }
  538. return $nested;
  539. }
  540. /**
  541. * Determine if the relationship is nested.
  542. *
  543. * @param string $relation
  544. * @param string $name
  545. * @return bool
  546. */
  547. protected function isNestedUnder($relation, $name)
  548. {
  549. return Str::contains($name, '.') && Str::startsWith($name, $relation.'.');
  550. }
  551. /**
  552. * Get a generator for the given query.
  553. *
  554. * @return \Generator
  555. */
  556. public function cursor()
  557. {
  558. foreach ($this->applyScopes()->query->cursor() as $record) {
  559. yield $this->model->newFromBuilder($record);
  560. }
  561. }
  562. /**
  563. * Chunk the results of a query by comparing numeric IDs.
  564. *
  565. * @param int $count
  566. * @param callable $callback
  567. * @param string|null $column
  568. * @param string|null $alias
  569. * @return bool
  570. */
  571. public function chunkById($count, callable $callback, $column = null, $alias = null)
  572. {
  573. $column = is_null($column) ? $this->getModel()->getKeyName() : $column;
  574. $alias = is_null($alias) ? $column : $alias;
  575. $lastId = null;
  576. do {
  577. $clone = clone $this;
  578. // We'll execute the query for the given page and get the results. If there are
  579. // no results we can just break and return from here. When there are results
  580. // we will call the callback with the current chunk of these results here.
  581. $results = $clone->forPageAfterId($count, $lastId, $column)->get();
  582. $countResults = $results->count();
  583. if ($countResults == 0) {
  584. break;
  585. }
  586. // On each chunk result set, we will pass them to the callback and then let the
  587. // developer take care of everything within the callback, which allows us to
  588. // keep the memory low for spinning through large result sets for working.
  589. if ($callback($results) === false) {
  590. return false;
  591. }
  592. $lastId = $results->last()->{$alias};
  593. unset($results);
  594. } while ($countResults == $count);
  595. return true;
  596. }
  597. /**
  598. * Add a generic "order by" clause if the query doesn't already have one.
  599. *
  600. * @return void
  601. */
  602. protected function enforceOrderBy()
  603. {
  604. if (empty($this->query->orders) && empty($this->query->unionOrders)) {
  605. $this->orderBy($this->model->getQualifiedKeyName(), 'asc');
  606. }
  607. }
  608. /**
  609. * Get an array with the values of a given column.
  610. *
  611. * @param string $column
  612. * @param string|null $key
  613. * @return \Illuminate\Support\Collection
  614. */
  615. public function pluck($column, $key = null)
  616. {
  617. $results = $this->toBase()->pluck($column, $key);
  618. // If the model has a mutator for the requested column, we will spin through
  619. // the results and mutate the values so that the mutated version of these
  620. // columns are returned as you would expect from these Eloquent models.
  621. if (! $this->model->hasGetMutator($column) &&
  622. ! $this->model->hasCast($column) &&
  623. ! in_array($column, $this->model->getDates())) {
  624. return $results;
  625. }
  626. return $results->map(function ($value) use ($column) {
  627. return $this->model->newFromBuilder([$column => $value])->{$column};
  628. });
  629. }
  630. /**
  631. * Paginate the given query.
  632. *
  633. * @param int $perPage
  634. * @param array $columns
  635. * @param string $pageName
  636. * @param int|null $page
  637. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  638. *
  639. * @throws \InvalidArgumentException
  640. */
  641. public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
  642. {
  643. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  644. $perPage = $perPage ?: $this->model->getPerPage();
  645. $results = ($total = $this->toBase()->getCountForPagination())
  646. ? $this->forPage($page, $perPage)->get($columns)
  647. : $this->model->newCollection();
  648. return $this->paginator($results, $total, $perPage, $page, [
  649. 'path' => Paginator::resolveCurrentPath(),
  650. 'pageName' => $pageName,
  651. ]);
  652. }
  653. /**
  654. * Paginate the given query into a simple paginator.
  655. *
  656. * @param int $perPage
  657. * @param array $columns
  658. * @param string $pageName
  659. * @param int|null $page
  660. * @return \Illuminate\Contracts\Pagination\Paginator
  661. */
  662. public function simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)
  663. {
  664. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  665. $perPage = $perPage ?: $this->model->getPerPage();
  666. // Next we will set the limit and offset for this query so that when we get the
  667. // results we get the proper section of results. Then, we'll create the full
  668. // paginator instances for these results with the given page and per page.
  669. $this->skip(($page - 1) * $perPage)->take($perPage + 1);
  670. return $this->simplePaginator($this->get($columns), $perPage, $page, [
  671. 'path' => Paginator::resolveCurrentPath(),
  672. 'pageName' => $pageName,
  673. ]);
  674. }
  675. /**
  676. * Save a new model and return the instance.
  677. *
  678. * @param array $attributes
  679. * @return \Illuminate\Database\Eloquent\Model|$this
  680. */
  681. public function create(array $attributes = [])
  682. {
  683. return tap($this->newModelInstance($attributes), function ($instance) {
  684. $instance->save();
  685. });
  686. }
  687. /**
  688. * Save a new model and return the instance. Allow mass-assignment.
  689. *
  690. * @param array $attributes
  691. * @return \Illuminate\Database\Eloquent\Model|$this
  692. */
  693. public function forceCreate(array $attributes)
  694. {
  695. return $this->model->unguarded(function () use ($attributes) {
  696. return $this->newModelInstance()->create($attributes);
  697. });
  698. }
  699. /**
  700. * Update a record in the database.
  701. *
  702. * @param array $values
  703. * @return int
  704. */
  705. public function update(array $values)
  706. {
  707. return $this->toBase()->update($this->addUpdatedAtColumn($values));
  708. }
  709. /**
  710. * Increment a column's value by a given amount.
  711. *
  712. * @param string $column
  713. * @param float|int $amount
  714. * @param array $extra
  715. * @return int
  716. */
  717. public function increment($column, $amount = 1, array $extra = [])
  718. {
  719. return $this->toBase()->increment(
  720. $column, $amount, $this->addUpdatedAtColumn($extra)
  721. );
  722. }
  723. /**
  724. * Decrement a column's value by a given amount.
  725. *
  726. * @param string $column
  727. * @param float|int $amount
  728. * @param array $extra
  729. * @return int
  730. */
  731. public function decrement($column, $amount = 1, array $extra = [])
  732. {
  733. return $this->toBase()->decrement(
  734. $column, $amount, $this->addUpdatedAtColumn($extra)
  735. );
  736. }
  737. /**
  738. * Add the "updated at" column to an array of values.
  739. *
  740. * @param array $values
  741. * @return array
  742. */
  743. protected function addUpdatedAtColumn(array $values)
  744. {
  745. if (! $this->model->usesTimestamps() ||
  746. is_null($this->model->getUpdatedAtColumn())) {
  747. return $values;
  748. }
  749. $column = $this->model->getUpdatedAtColumn();
  750. $values = array_merge(
  751. [$column => $this->model->freshTimestampString()],
  752. $values
  753. );
  754. $values[$this->qualifyColumn($column)] = $values[$column];
  755. unset($values[$column]);
  756. return $values;
  757. }
  758. /**
  759. * Delete a record from the database.
  760. *
  761. * @return mixed
  762. */
  763. public function delete()
  764. {
  765. if (isset($this->onDelete)) {
  766. return call_user_func($this->onDelete, $this);
  767. }
  768. return $this->toBase()->delete();
  769. }
  770. /**
  771. * Run the default delete function on the builder.
  772. *
  773. * Since we do not apply scopes here, the row will actually be deleted.
  774. *
  775. * @return mixed
  776. */
  777. public function forceDelete()
  778. {
  779. return $this->query->delete();
  780. }
  781. /**
  782. * Register a replacement for the default delete function.
  783. *
  784. * @param \Closure $callback
  785. * @return void
  786. */
  787. public function onDelete(Closure $callback)
  788. {
  789. $this->onDelete = $callback;
  790. }
  791. /**
  792. * Call the given local model scopes.
  793. *
  794. * @param array $scopes
  795. * @return static|mixed
  796. */
  797. public function scopes(array $scopes)
  798. {
  799. $builder = $this;
  800. foreach ($scopes as $scope => $parameters) {
  801. // If the scope key is an integer, then the scope was passed as the value and
  802. // the parameter list is empty, so we will format the scope name and these
  803. // parameters here. Then, we'll be ready to call the scope on the model.
  804. if (is_int($scope)) {
  805. [$scope, $parameters] = [$parameters, []];
  806. }
  807. // Next we'll pass the scope callback to the callScope method which will take
  808. // care of grouping the "wheres" properly so the logical order doesn't get
  809. // messed up when adding scopes. Then we'll return back out the builder.
  810. $builder = $builder->callScope(
  811. [$this->model, 'scope'.ucfirst($scope)],
  812. (array) $parameters
  813. );
  814. }
  815. return $builder;
  816. }
  817. /**
  818. * Apply the scopes to the Eloquent builder instance and return it.
  819. *
  820. * @return static
  821. */
  822. public function applyScopes()
  823. {
  824. if (! $this->scopes) {
  825. return $this;
  826. }
  827. $builder = clone $this;
  828. foreach ($this->scopes as $identifier => $scope) {
  829. if (! isset($builder->scopes[$identifier])) {
  830. continue;
  831. }
  832. $builder->callScope(function (Builder $builder) use ($scope) {
  833. // If the scope is a Closure we will just go ahead and call the scope with the
  834. // builder instance. The "callScope" method will properly group the clauses
  835. // that are added to this query so "where" clauses maintain proper logic.
  836. if ($scope instanceof Closure) {
  837. $scope($builder);
  838. }
  839. // If the scope is a scope object, we will call the apply method on this scope
  840. // passing in the builder and the model instance. After we run all of these
  841. // scopes we will return back the builder instance to the outside caller.
  842. if ($scope instanceof Scope) {
  843. $scope->apply($builder, $this->getModel());
  844. }
  845. });
  846. }
  847. return $builder;
  848. }
  849. /**
  850. * Apply the given scope on the current builder instance.
  851. *
  852. * @param callable $scope
  853. * @param array $parameters
  854. * @return mixed
  855. */
  856. protected function callScope(callable $scope, $parameters = [])
  857. {
  858. array_unshift($parameters, $this);
  859. $query = $this->getQuery();
  860. // We will keep track of how many wheres are on the query before running the
  861. // scope so that we can properly group the added scope constraints in the
  862. // query as their own isolated nested where statement and avoid issues.
  863. $originalWhereCount = is_null($query->wheres)
  864. ? 0 : count($query->wheres);
  865. $result = $scope(...array_values($parameters)) ?? $this;
  866. if (count((array) $query->wheres) > $originalWhereCount) {
  867. $this->addNewWheresWithinGroup($query, $originalWhereCount);
  868. }
  869. return $result;
  870. }
  871. /**
  872. * Nest where conditions by slicing them at the given where count.
  873. *
  874. * @param \Illuminate\Database\Query\Builder $query
  875. * @param int $originalWhereCount
  876. * @return void
  877. */
  878. protected function addNewWheresWithinGroup(QueryBuilder $query, $originalWhereCount)
  879. {
  880. // Here, we totally remove all of the where clauses since we are going to
  881. // rebuild them as nested queries by slicing the groups of wheres into
  882. // their own sections. This is to prevent any confusing logic order.
  883. $allWheres = $query->wheres;
  884. $query->wheres = [];
  885. $this->groupWhereSliceForScope(
  886. $query, array_slice($allWheres, 0, $originalWhereCount)
  887. );
  888. $this->groupWhereSliceForScope(
  889. $query, array_slice($allWheres, $originalWhereCount)
  890. );
  891. }
  892. /**
  893. * Slice where conditions at the given offset and add them to the query as a nested condition.
  894. *
  895. * @param \Illuminate\Database\Query\Builder $query
  896. * @param array $whereSlice
  897. * @return void
  898. */
  899. protected function groupWhereSliceForScope(QueryBuilder $query, $whereSlice)
  900. {
  901. $whereBooleans = collect($whereSlice)->pluck('boolean');
  902. // Here we'll check if the given subset of where clauses contains any "or"
  903. // booleans and in this case create a nested where expression. That way
  904. // we don't add any unnecessary nesting thus keeping the query clean.
  905. if ($whereBooleans->contains('or')) {
  906. $query->wheres[] = $this->createNestedWhere(
  907. $whereSlice, $whereBooleans->first()
  908. );
  909. } else {
  910. $query->wheres = array_merge($query->wheres, $whereSlice);
  911. }
  912. }
  913. /**
  914. * Create a where array with nested where conditions.
  915. *
  916. * @param array $whereSlice
  917. * @param string $boolean
  918. * @return array
  919. */
  920. protected function createNestedWhere($whereSlice, $boolean = 'and')
  921. {
  922. $whereGroup = $this->getQuery()->forNestedWhere();
  923. $whereGroup->wheres = $whereSlice;
  924. return ['type' => 'Nested', 'query' => $whereGroup, 'boolean' => $boolean];
  925. }
  926. /**
  927. * Set the relationships that should be eager loaded.
  928. *
  929. * @param mixed $relations
  930. * @return $this
  931. */
  932. public function with($relations)
  933. {
  934. $eagerLoad = $this->parseWithRelations(is_string($relations) ? func_get_args() : $relations);
  935. $this->eagerLoad = array_merge($this->eagerLoad, $eagerLoad);
  936. return $this;
  937. }
  938. /**
  939. * Prevent the specified relations from being eager loaded.
  940. *
  941. * @param mixed $relations
  942. * @return $this
  943. */
  944. public function without($relations)
  945. {
  946. $this->eagerLoad = array_diff_key($this->eagerLoad, array_flip(
  947. is_string($relations) ? func_get_args() : $relations
  948. ));
  949. return $this;
  950. }
  951. /**
  952. * Create a new instance of the model being queried.
  953. *
  954. * @param array $attributes
  955. * @return \Illuminate\Database\Eloquent\Model|static
  956. */
  957. public function newModelInstance($attributes = [])
  958. {
  959. return $this->model->newInstance($attributes)->setConnection(
  960. $this->query->getConnection()->getName()
  961. );
  962. }
  963. /**
  964. * Parse a list of relations into individuals.
  965. *
  966. * @param array $relations
  967. * @return array
  968. */
  969. protected function parseWithRelations(array $relations)
  970. {
  971. $results = [];
  972. foreach ($relations as $name => $constraints) {
  973. // If the "name" value is a numeric key, we can assume that no
  974. // constraints have been specified. We'll just put an empty
  975. // Closure there, so that we can treat them all the same.
  976. if (is_numeric($name)) {
  977. $name = $constraints;
  978. [$name, $constraints] = Str::contains($name, ':')
  979. ? $this->createSelectWithConstraint($name)
  980. : [$name, function () {
  981. //
  982. }];
  983. }
  984. // We need to separate out any nested includes, which allows the developers
  985. // to load deep relationships using "dots" without stating each level of
  986. // the relationship with its own key in the array of eager-load names.
  987. $results = $this->addNestedWiths($name, $results);
  988. $results[$name] = $constraints;
  989. }
  990. return $results;
  991. }
  992. /**
  993. * Create a constraint to select the given columns for the relation.
  994. *
  995. * @param string $name
  996. * @return array
  997. */
  998. protected function createSelectWithConstraint($name)
  999. {
  1000. return [explode(':', $name)[0], function ($query) use ($name) {
  1001. $query->select(explode(',', explode(':', $name)[1]));
  1002. }];
  1003. }
  1004. /**
  1005. * Parse the nested relationships in a relation.
  1006. *
  1007. * @param string $name
  1008. * @param array $results
  1009. * @return array
  1010. */
  1011. protected function addNestedWiths($name, $results)
  1012. {
  1013. $progress = [];
  1014. // If the relation has already been set on the result array, we will not set it
  1015. // again, since that would override any constraints that were already placed
  1016. // on the relationships. We will only set the ones that are not specified.
  1017. foreach (explode('.', $name) as $segment) {
  1018. $progress[] = $segment;
  1019. if (! isset($results[$last = implode('.', $progress)])) {
  1020. $results[$last] = function () {
  1021. //
  1022. };
  1023. }
  1024. }
  1025. return $results;
  1026. }
  1027. /**
  1028. * Get the underlying query builder instance.
  1029. *
  1030. * @return \Illuminate\Database\Query\Builder
  1031. */
  1032. public function getQuery()
  1033. {
  1034. return $this->query;
  1035. }
  1036. /**
  1037. * Set the underlying query builder instance.
  1038. *
  1039. * @param \Illuminate\Database\Query\Builder $query
  1040. * @return $this
  1041. */
  1042. public function setQuery($query)
  1043. {
  1044. $this->query = $query;
  1045. return $this;
  1046. }
  1047. /**
  1048. * Get a base query builder instance.
  1049. *
  1050. * @return \Illuminate\Database\Query\Builder
  1051. */
  1052. public function toBase()
  1053. {
  1054. return $this->applyScopes()->getQuery();
  1055. }
  1056. /**
  1057. * Get the relationships being eagerly loaded.
  1058. *
  1059. * @return array
  1060. */
  1061. public function getEagerLoads()
  1062. {
  1063. return $this->eagerLoad;
  1064. }
  1065. /**
  1066. * Set the relationships being eagerly loaded.
  1067. *
  1068. * @param array $eagerLoad
  1069. * @return $this
  1070. */
  1071. public function setEagerLoads(array $eagerLoad)
  1072. {
  1073. $this->eagerLoad = $eagerLoad;
  1074. return $this;
  1075. }
  1076. /**
  1077. * Get the model instance being queried.
  1078. *
  1079. * @return \Illuminate\Database\Eloquent\Model|static
  1080. */
  1081. public function getModel()
  1082. {
  1083. return $this->model;
  1084. }
  1085. /**
  1086. * Set a model instance for the model being queried.
  1087. *
  1088. * @param \Illuminate\Database\Eloquent\Model $model
  1089. * @return $this
  1090. */
  1091. public function setModel(Model $model)
  1092. {
  1093. $this->model = $model;
  1094. $this->query->from($model->getTable());
  1095. return $this;
  1096. }
  1097. /**
  1098. * Qualify the given column name by the model's table.
  1099. *
  1100. * @param string $column
  1101. * @return string
  1102. */
  1103. public function qualifyColumn($column)
  1104. {
  1105. return $this->model->qualifyColumn($column);
  1106. }
  1107. /**
  1108. * Get the given macro by name.
  1109. *
  1110. * @param string $name
  1111. * @return \Closure
  1112. */
  1113. public function getMacro($name)
  1114. {
  1115. return Arr::get($this->localMacros, $name);
  1116. }
  1117. /**
  1118. * Dynamically access builder proxies.
  1119. *
  1120. * @param string $key
  1121. * @return mixed
  1122. *
  1123. * @throws \Exception
  1124. */
  1125. public function __get($key)
  1126. {
  1127. if ($key === 'orWhere') {
  1128. return new HigherOrderBuilderProxy($this, $key);
  1129. }
  1130. throw new Exception("Property [{$key}] does not exist on the Eloquent builder instance.");
  1131. }
  1132. /**
  1133. * Dynamically handle calls into the query instance.
  1134. *
  1135. * @param string $method
  1136. * @param array $parameters
  1137. * @return mixed
  1138. */
  1139. public function __call($method, $parameters)
  1140. {
  1141. if ($method === 'macro') {
  1142. $this->localMacros[$parameters[0]] = $parameters[1];
  1143. return;
  1144. }
  1145. if (isset($this->localMacros[$method])) {
  1146. array_unshift($parameters, $this);
  1147. return $this->localMacros[$method](...$parameters);
  1148. }
  1149. if (isset(static::$macros[$method])) {
  1150. if (static::$macros[$method] instanceof Closure) {
  1151. return call_user_func_array(static::$macros[$method]->bindTo($this, static::class), $parameters);
  1152. }
  1153. return call_user_func_array(static::$macros[$method], $parameters);
  1154. }
  1155. if (method_exists($this->model, $scope = 'scope'.ucfirst($method))) {
  1156. return $this->callScope([$this->model, $scope], $parameters);
  1157. }
  1158. if (in_array($method, $this->passthru)) {
  1159. return $this->toBase()->{$method}(...$parameters);
  1160. }
  1161. $this->forwardCallTo($this->query, $method, $parameters);
  1162. return $this;
  1163. }
  1164. /**
  1165. * Dynamically handle calls into the query instance.
  1166. *
  1167. * @param string $method
  1168. * @param array $parameters
  1169. * @return mixed
  1170. *
  1171. * @throws \BadMethodCallException
  1172. */
  1173. public static function __callStatic($method, $parameters)
  1174. {
  1175. if ($method === 'macro') {
  1176. static::$macros[$parameters[0]] = $parameters[1];
  1177. return;
  1178. }
  1179. if (! isset(static::$macros[$method])) {
  1180. static::throwBadMethodCallException($method);
  1181. }
  1182. if (static::$macros[$method] instanceof Closure) {
  1183. return call_user_func_array(Closure::bind(static::$macros[$method], null, static::class), $parameters);
  1184. }
  1185. return call_user_func_array(static::$macros[$method], $parameters);
  1186. }
  1187. /**
  1188. * Force a clone of the underlying query builder when cloning.
  1189. *
  1190. * @return void
  1191. */
  1192. public function __clone()
  1193. {
  1194. $this->query = clone $this->query;
  1195. }
  1196. }