Builder.php 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485
  1. <?php
  2. namespace Illuminate\Database\Query;
  3. use Closure;
  4. use RuntimeException;
  5. use BadMethodCallException;
  6. use Illuminate\Support\Arr;
  7. use Illuminate\Support\Str;
  8. use InvalidArgumentException;
  9. use Illuminate\Support\Collection;
  10. use Illuminate\Pagination\Paginator;
  11. use Illuminate\Support\Traits\Macroable;
  12. use Illuminate\Contracts\Support\Arrayable;
  13. use Illuminate\Database\ConnectionInterface;
  14. use Illuminate\Database\Concerns\BuildsQueries;
  15. use Illuminate\Database\Query\Grammars\Grammar;
  16. use Illuminate\Database\Query\Processors\Processor;
  17. use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
  18. class Builder
  19. {
  20. use BuildsQueries, Macroable {
  21. __call as macroCall;
  22. }
  23. /**
  24. * The database connection instance.
  25. *
  26. * @var \Illuminate\Database\ConnectionInterface
  27. */
  28. public $connection;
  29. /**
  30. * The database query grammar instance.
  31. *
  32. * @var \Illuminate\Database\Query\Grammars\Grammar
  33. */
  34. public $grammar;
  35. /**
  36. * The database query post processor instance.
  37. *
  38. * @var \Illuminate\Database\Query\Processors\Processor
  39. */
  40. public $processor;
  41. /**
  42. * The current query value bindings.
  43. *
  44. * @var array
  45. */
  46. public $bindings = [
  47. 'select' => [],
  48. 'join' => [],
  49. 'where' => [],
  50. 'having' => [],
  51. 'order' => [],
  52. 'union' => [],
  53. ];
  54. /**
  55. * An aggregate function and column to be run.
  56. *
  57. * @var array
  58. */
  59. public $aggregate;
  60. /**
  61. * The columns that should be returned.
  62. *
  63. * @var array
  64. */
  65. public $columns;
  66. /**
  67. * Indicates if the query returns distinct results.
  68. *
  69. * @var bool
  70. */
  71. public $distinct = false;
  72. /**
  73. * The table which the query is targeting.
  74. *
  75. * @var string
  76. */
  77. public $from;
  78. /**
  79. * The table joins for the query.
  80. *
  81. * @var array
  82. */
  83. public $joins;
  84. /**
  85. * The where constraints for the query.
  86. *
  87. * @var array
  88. */
  89. public $wheres = [];
  90. /**
  91. * The groupings for the query.
  92. *
  93. * @var array
  94. */
  95. public $groups;
  96. /**
  97. * The having constraints for the query.
  98. *
  99. * @var array
  100. */
  101. public $havings;
  102. /**
  103. * The orderings for the query.
  104. *
  105. * @var array
  106. */
  107. public $orders;
  108. /**
  109. * The maximum number of records to return.
  110. *
  111. * @var int
  112. */
  113. public $limit;
  114. /**
  115. * The number of records to skip.
  116. *
  117. * @var int
  118. */
  119. public $offset;
  120. /**
  121. * The query union statements.
  122. *
  123. * @var array
  124. */
  125. public $unions;
  126. /**
  127. * The maximum number of union records to return.
  128. *
  129. * @var int
  130. */
  131. public $unionLimit;
  132. /**
  133. * The number of union records to skip.
  134. *
  135. * @var int
  136. */
  137. public $unionOffset;
  138. /**
  139. * The orderings for the union query.
  140. *
  141. * @var array
  142. */
  143. public $unionOrders;
  144. /**
  145. * Indicates whether row locking is being used.
  146. *
  147. * @var string|bool
  148. */
  149. public $lock;
  150. /**
  151. * All of the available clause operators.
  152. *
  153. * @var array
  154. */
  155. public $operators = [
  156. '=', '<', '>', '<=', '>=', '<>', '!=', '<=>',
  157. 'like', 'like binary', 'not like', 'ilike',
  158. '&', '|', '^', '<<', '>>',
  159. 'rlike', 'regexp', 'not regexp',
  160. '~', '~*', '!~', '!~*', 'similar to',
  161. 'not similar to', 'not ilike', '~~*', '!~~*',
  162. ];
  163. /**
  164. * Whether use write pdo for select.
  165. *
  166. * @var bool
  167. */
  168. public $useWritePdo = false;
  169. /**
  170. * Create a new query builder instance.
  171. *
  172. * @param \Illuminate\Database\ConnectionInterface $connection
  173. * @param \Illuminate\Database\Query\Grammars\Grammar $grammar
  174. * @param \Illuminate\Database\Query\Processors\Processor $processor
  175. * @return void
  176. */
  177. public function __construct(ConnectionInterface $connection,
  178. Grammar $grammar = null,
  179. Processor $processor = null)
  180. {
  181. $this->connection = $connection;
  182. $this->grammar = $grammar ?: $connection->getQueryGrammar();
  183. $this->processor = $processor ?: $connection->getPostProcessor();
  184. }
  185. /**
  186. * Set the columns to be selected.
  187. *
  188. * @param array|mixed $columns
  189. * @return $this
  190. */
  191. public function select($columns = ['*'])
  192. {
  193. $this->columns = is_array($columns) ? $columns : func_get_args();
  194. return $this;
  195. }
  196. /**
  197. * Add a new "raw" select expression to the query.
  198. *
  199. * @param string $expression
  200. * @param array $bindings
  201. * @return \Illuminate\Database\Query\Builder|static
  202. */
  203. public function selectRaw($expression, array $bindings = [])
  204. {
  205. $this->addSelect(new Expression($expression));
  206. if ($bindings) {
  207. $this->addBinding($bindings, 'select');
  208. }
  209. return $this;
  210. }
  211. /**
  212. * Add a subselect expression to the query.
  213. *
  214. * @param \Closure|\Illuminate\Database\Query\Builder|string $query
  215. * @param string $as
  216. * @return \Illuminate\Database\Query\Builder|static
  217. *
  218. * @throws \InvalidArgumentException
  219. */
  220. public function selectSub($query, $as)
  221. {
  222. // If the given query is a Closure, we will execute it while passing in a new
  223. // query instance to the Closure. This will give the developer a chance to
  224. // format and work with the query before we cast it to a raw SQL string.
  225. if ($query instanceof Closure) {
  226. $callback = $query;
  227. $callback($query = $this->forSubQuery());
  228. }
  229. // Here, we will parse this query into an SQL string and an array of bindings
  230. // so we can add it to the query builder using the selectRaw method so the
  231. // query is included in the real SQL generated by this builder instance.
  232. list($query, $bindings) = $this->parseSubSelect($query);
  233. return $this->selectRaw(
  234. '('.$query.') as '.$this->grammar->wrap($as), $bindings
  235. );
  236. }
  237. /**
  238. * Parse the sub-select query into SQL and bindings.
  239. *
  240. * @param mixed $query
  241. * @return array
  242. */
  243. protected function parseSubSelect($query)
  244. {
  245. if ($query instanceof self) {
  246. $query->columns = [$query->columns[0]];
  247. return [$query->toSql(), $query->getBindings()];
  248. } elseif (is_string($query)) {
  249. return [$query, []];
  250. } else {
  251. throw new InvalidArgumentException;
  252. }
  253. }
  254. /**
  255. * Add a new select column to the query.
  256. *
  257. * @param array|mixed $column
  258. * @return $this
  259. */
  260. public function addSelect($column)
  261. {
  262. $column = is_array($column) ? $column : func_get_args();
  263. $this->columns = array_merge((array) $this->columns, $column);
  264. return $this;
  265. }
  266. /**
  267. * Force the query to only return distinct results.
  268. *
  269. * @return $this
  270. */
  271. public function distinct()
  272. {
  273. $this->distinct = true;
  274. return $this;
  275. }
  276. /**
  277. * Set the table which the query is targeting.
  278. *
  279. * @param string $table
  280. * @return $this
  281. */
  282. public function from($table)
  283. {
  284. $this->from = $table;
  285. return $this;
  286. }
  287. /**
  288. * Add a join clause to the query.
  289. *
  290. * @param string $table
  291. * @param string $first
  292. * @param string|null $operator
  293. * @param string|null $second
  294. * @param string $type
  295. * @param bool $where
  296. * @return $this
  297. */
  298. public function join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false)
  299. {
  300. $join = new JoinClause($this, $type, $table);
  301. // If the first "column" of the join is really a Closure instance the developer
  302. // is trying to build a join with a complex "on" clause containing more than
  303. // one condition, so we'll add the join and call a Closure with the query.
  304. if ($first instanceof Closure) {
  305. call_user_func($first, $join);
  306. $this->joins[] = $join;
  307. $this->addBinding($join->getBindings(), 'join');
  308. }
  309. // If the column is simply a string, we can assume the join simply has a basic
  310. // "on" clause with a single condition. So we will just build the join with
  311. // this simple join clauses attached to it. There is not a join callback.
  312. else {
  313. $method = $where ? 'where' : 'on';
  314. $this->joins[] = $join->$method($first, $operator, $second);
  315. $this->addBinding($join->getBindings(), 'join');
  316. }
  317. return $this;
  318. }
  319. /**
  320. * Add a "join where" clause to the query.
  321. *
  322. * @param string $table
  323. * @param string $first
  324. * @param string $operator
  325. * @param string $second
  326. * @param string $type
  327. * @return \Illuminate\Database\Query\Builder|static
  328. */
  329. public function joinWhere($table, $first, $operator, $second, $type = 'inner')
  330. {
  331. return $this->join($table, $first, $operator, $second, $type, true);
  332. }
  333. /**
  334. * Add a left join to the query.
  335. *
  336. * @param string $table
  337. * @param string $first
  338. * @param string|null $operator
  339. * @param string|null $second
  340. * @return \Illuminate\Database\Query\Builder|static
  341. */
  342. public function leftJoin($table, $first, $operator = null, $second = null)
  343. {
  344. return $this->join($table, $first, $operator, $second, 'left');
  345. }
  346. /**
  347. * Add a "join where" clause to the query.
  348. *
  349. * @param string $table
  350. * @param string $first
  351. * @param string $operator
  352. * @param string $second
  353. * @return \Illuminate\Database\Query\Builder|static
  354. */
  355. public function leftJoinWhere($table, $first, $operator, $second)
  356. {
  357. return $this->joinWhere($table, $first, $operator, $second, 'left');
  358. }
  359. /**
  360. * Add a right join to the query.
  361. *
  362. * @param string $table
  363. * @param string $first
  364. * @param string|null $operator
  365. * @param string|null $second
  366. * @return \Illuminate\Database\Query\Builder|static
  367. */
  368. public function rightJoin($table, $first, $operator = null, $second = null)
  369. {
  370. return $this->join($table, $first, $operator, $second, 'right');
  371. }
  372. /**
  373. * Add a "right join where" clause to the query.
  374. *
  375. * @param string $table
  376. * @param string $first
  377. * @param string $operator
  378. * @param string $second
  379. * @return \Illuminate\Database\Query\Builder|static
  380. */
  381. public function rightJoinWhere($table, $first, $operator, $second)
  382. {
  383. return $this->joinWhere($table, $first, $operator, $second, 'right');
  384. }
  385. /**
  386. * Add a "cross join" clause to the query.
  387. *
  388. * @param string $table
  389. * @param string|null $first
  390. * @param string|null $operator
  391. * @param string|null $second
  392. * @return \Illuminate\Database\Query\Builder|static
  393. */
  394. public function crossJoin($table, $first = null, $operator = null, $second = null)
  395. {
  396. if ($first) {
  397. return $this->join($table, $first, $operator, $second, 'cross');
  398. }
  399. $this->joins[] = new JoinClause($this, 'cross', $table);
  400. return $this;
  401. }
  402. /**
  403. * Merge an array of where clauses and bindings.
  404. *
  405. * @param array $wheres
  406. * @param array $bindings
  407. * @return void
  408. */
  409. public function mergeWheres($wheres, $bindings)
  410. {
  411. $this->wheres = array_merge($this->wheres, (array) $wheres);
  412. $this->bindings['where'] = array_values(
  413. array_merge($this->bindings['where'], (array) $bindings)
  414. );
  415. }
  416. /**
  417. * Add a basic where clause to the query.
  418. *
  419. * @param string|array|\Closure $column
  420. * @param mixed $operator
  421. * @param mixed $value
  422. * @param string $boolean
  423. * @return $this
  424. */
  425. public function where($column, $operator = null, $value = null, $boolean = 'and')
  426. {
  427. // If the column is an array, we will assume it is an array of key-value pairs
  428. // and can add them each as a where clause. We will maintain the boolean we
  429. // received when the method was called and pass it into the nested where.
  430. if (is_array($column)) {
  431. return $this->addArrayOfWheres($column, $boolean);
  432. }
  433. // Here we will make some assumptions about the operator. If only 2 values are
  434. // passed to the method, we will assume that the operator is an equals sign
  435. // and keep going. Otherwise, we'll require the operator to be passed in.
  436. list($value, $operator) = $this->prepareValueAndOperator(
  437. $value, $operator, func_num_args() == 2
  438. );
  439. // If the columns is actually a Closure instance, we will assume the developer
  440. // wants to begin a nested where statement which is wrapped in parenthesis.
  441. // We'll add that Closure to the query then return back out immediately.
  442. if ($column instanceof Closure) {
  443. return $this->whereNested($column, $boolean);
  444. }
  445. // If the given operator is not found in the list of valid operators we will
  446. // assume that the developer is just short-cutting the '=' operators and
  447. // we will set the operators to '=' and set the values appropriately.
  448. if ($this->invalidOperator($operator)) {
  449. list($value, $operator) = [$operator, '='];
  450. }
  451. // If the value is a Closure, it means the developer is performing an entire
  452. // sub-select within the query and we will need to compile the sub-select
  453. // within the where clause to get the appropriate query record results.
  454. if ($value instanceof Closure) {
  455. return $this->whereSub($column, $operator, $value, $boolean);
  456. }
  457. // If the value is "null", we will just assume the developer wants to add a
  458. // where null clause to the query. So, we will allow a short-cut here to
  459. // that method for convenience so the developer doesn't have to check.
  460. if (is_null($value)) {
  461. return $this->whereNull($column, $boolean, $operator !== '=');
  462. }
  463. // If the column is making a JSON reference we'll check to see if the value
  464. // is a boolean. If it is, we'll add the raw boolean string as an actual
  465. // value to the query to ensure this is properly handled by the query.
  466. if (Str::contains($column, '->') && is_bool($value)) {
  467. $value = new Expression($value ? 'true' : 'false');
  468. }
  469. // Now that we are working with just a simple query we can put the elements
  470. // in our array and add the query binding to our array of bindings that
  471. // will be bound to each SQL statements when it is finally executed.
  472. $type = 'Basic';
  473. $this->wheres[] = compact(
  474. 'type', 'column', 'operator', 'value', 'boolean'
  475. );
  476. if (! $value instanceof Expression) {
  477. $this->addBinding($value, 'where');
  478. }
  479. return $this;
  480. }
  481. /**
  482. * Add an array of where clauses to the query.
  483. *
  484. * @param array $column
  485. * @param string $boolean
  486. * @param string $method
  487. * @return $this
  488. */
  489. protected function addArrayOfWheres($column, $boolean, $method = 'where')
  490. {
  491. return $this->whereNested(function ($query) use ($column, $method, $boolean) {
  492. foreach ($column as $key => $value) {
  493. if (is_numeric($key) && is_array($value)) {
  494. $query->{$method}(...array_values($value));
  495. } else {
  496. $query->$method($key, '=', $value, $boolean);
  497. }
  498. }
  499. }, $boolean);
  500. }
  501. /**
  502. * Prepare the value and operator for a where clause.
  503. *
  504. * @param string $value
  505. * @param string $operator
  506. * @param bool $useDefault
  507. * @return array
  508. *
  509. * @throws \InvalidArgumentException
  510. */
  511. public function prepareValueAndOperator($value, $operator, $useDefault = false)
  512. {
  513. if ($useDefault) {
  514. return [$operator, '='];
  515. } elseif ($this->invalidOperatorAndValue($operator, $value)) {
  516. throw new InvalidArgumentException('Illegal operator and value combination.');
  517. }
  518. return [$value, $operator];
  519. }
  520. /**
  521. * Determine if the given operator and value combination is legal.
  522. *
  523. * Prevents using Null values with invalid operators.
  524. *
  525. * @param string $operator
  526. * @param mixed $value
  527. * @return bool
  528. */
  529. protected function invalidOperatorAndValue($operator, $value)
  530. {
  531. return is_null($value) && in_array($operator, $this->operators) &&
  532. ! in_array($operator, ['=', '<>', '!=']);
  533. }
  534. /**
  535. * Determine if the given operator is supported.
  536. *
  537. * @param string $operator
  538. * @return bool
  539. */
  540. protected function invalidOperator($operator)
  541. {
  542. return ! in_array(strtolower($operator), $this->operators, true) &&
  543. ! in_array(strtolower($operator), $this->grammar->getOperators(), true);
  544. }
  545. /**
  546. * Add an "or where" clause to the query.
  547. *
  548. * @param string|array|\Closure $column
  549. * @param string|null $operator
  550. * @param mixed $value
  551. * @return \Illuminate\Database\Query\Builder|static
  552. */
  553. public function orWhere($column, $operator = null, $value = null)
  554. {
  555. list($value, $operator) = $this->prepareValueAndOperator(
  556. $value, $operator, func_num_args() == 2
  557. );
  558. return $this->where($column, $operator, $value, 'or');
  559. }
  560. /**
  561. * Add a "where" clause comparing two columns to the query.
  562. *
  563. * @param string|array $first
  564. * @param string|null $operator
  565. * @param string|null $second
  566. * @param string|null $boolean
  567. * @return \Illuminate\Database\Query\Builder|static
  568. */
  569. public function whereColumn($first, $operator = null, $second = null, $boolean = 'and')
  570. {
  571. // If the column is an array, we will assume it is an array of key-value pairs
  572. // and can add them each as a where clause. We will maintain the boolean we
  573. // received when the method was called and pass it into the nested where.
  574. if (is_array($first)) {
  575. return $this->addArrayOfWheres($first, $boolean, 'whereColumn');
  576. }
  577. // If the given operator is not found in the list of valid operators we will
  578. // assume that the developer is just short-cutting the '=' operators and
  579. // we will set the operators to '=' and set the values appropriately.
  580. if ($this->invalidOperator($operator)) {
  581. list($second, $operator) = [$operator, '='];
  582. }
  583. // Finally, we will add this where clause into this array of clauses that we
  584. // are building for the query. All of them will be compiled via a grammar
  585. // once the query is about to be executed and run against the database.
  586. $type = 'Column';
  587. $this->wheres[] = compact(
  588. 'type', 'first', 'operator', 'second', 'boolean'
  589. );
  590. return $this;
  591. }
  592. /**
  593. * Add an "or where" clause comparing two columns to the query.
  594. *
  595. * @param string|array $first
  596. * @param string|null $operator
  597. * @param string|null $second
  598. * @return \Illuminate\Database\Query\Builder|static
  599. */
  600. public function orWhereColumn($first, $operator = null, $second = null)
  601. {
  602. return $this->whereColumn($first, $operator, $second, 'or');
  603. }
  604. /**
  605. * Add a raw where clause to the query.
  606. *
  607. * @param string $sql
  608. * @param mixed $bindings
  609. * @param string $boolean
  610. * @return $this
  611. */
  612. public function whereRaw($sql, $bindings = [], $boolean = 'and')
  613. {
  614. $this->wheres[] = ['type' => 'raw', 'sql' => $sql, 'boolean' => $boolean];
  615. $this->addBinding((array) $bindings, 'where');
  616. return $this;
  617. }
  618. /**
  619. * Add a raw or where clause to the query.
  620. *
  621. * @param string $sql
  622. * @param mixed $bindings
  623. * @return \Illuminate\Database\Query\Builder|static
  624. */
  625. public function orWhereRaw($sql, $bindings = [])
  626. {
  627. return $this->whereRaw($sql, $bindings, 'or');
  628. }
  629. /**
  630. * Add a "where in" clause to the query.
  631. *
  632. * @param string $column
  633. * @param mixed $values
  634. * @param string $boolean
  635. * @param bool $not
  636. * @return $this
  637. */
  638. public function whereIn($column, $values, $boolean = 'and', $not = false)
  639. {
  640. $type = $not ? 'NotIn' : 'In';
  641. if ($values instanceof EloquentBuilder) {
  642. $values = $values->getQuery();
  643. }
  644. // If the value is a query builder instance we will assume the developer wants to
  645. // look for any values that exists within this given query. So we will add the
  646. // query accordingly so that this query is properly executed when it is run.
  647. if ($values instanceof self) {
  648. return $this->whereInExistingQuery(
  649. $column, $values, $boolean, $not
  650. );
  651. }
  652. // If the value of the where in clause is actually a Closure, we will assume that
  653. // the developer is using a full sub-select for this "in" statement, and will
  654. // execute those Closures, then we can re-construct the entire sub-selects.
  655. if ($values instanceof Closure) {
  656. return $this->whereInSub($column, $values, $boolean, $not);
  657. }
  658. // Next, if the value is Arrayable we need to cast it to its raw array form so we
  659. // have the underlying array value instead of an Arrayable object which is not
  660. // able to be added as a binding, etc. We will then add to the wheres array.
  661. if ($values instanceof Arrayable) {
  662. $values = $values->toArray();
  663. }
  664. $this->wheres[] = compact('type', 'column', 'values', 'boolean');
  665. // Finally we'll add a binding for each values unless that value is an expression
  666. // in which case we will just skip over it since it will be the query as a raw
  667. // string and not as a parameterized place-holder to be replaced by the PDO.
  668. foreach ($values as $value) {
  669. if (! $value instanceof Expression) {
  670. $this->addBinding($value, 'where');
  671. }
  672. }
  673. return $this;
  674. }
  675. /**
  676. * Add an "or where in" clause to the query.
  677. *
  678. * @param string $column
  679. * @param mixed $values
  680. * @return \Illuminate\Database\Query\Builder|static
  681. */
  682. public function orWhereIn($column, $values)
  683. {
  684. return $this->whereIn($column, $values, 'or');
  685. }
  686. /**
  687. * Add a "where not in" clause to the query.
  688. *
  689. * @param string $column
  690. * @param mixed $values
  691. * @param string $boolean
  692. * @return \Illuminate\Database\Query\Builder|static
  693. */
  694. public function whereNotIn($column, $values, $boolean = 'and')
  695. {
  696. return $this->whereIn($column, $values, $boolean, true);
  697. }
  698. /**
  699. * Add an "or where not in" clause to the query.
  700. *
  701. * @param string $column
  702. * @param mixed $values
  703. * @return \Illuminate\Database\Query\Builder|static
  704. */
  705. public function orWhereNotIn($column, $values)
  706. {
  707. return $this->whereNotIn($column, $values, 'or');
  708. }
  709. /**
  710. * Add a where in with a sub-select to the query.
  711. *
  712. * @param string $column
  713. * @param \Closure $callback
  714. * @param string $boolean
  715. * @param bool $not
  716. * @return $this
  717. */
  718. protected function whereInSub($column, Closure $callback, $boolean, $not)
  719. {
  720. $type = $not ? 'NotInSub' : 'InSub';
  721. // To create the exists sub-select, we will actually create a query and call the
  722. // provided callback with the query so the developer may set any of the query
  723. // conditions they want for the in clause, then we'll put it in this array.
  724. call_user_func($callback, $query = $this->forSubQuery());
  725. $this->wheres[] = compact('type', 'column', 'query', 'boolean');
  726. $this->addBinding($query->getBindings(), 'where');
  727. return $this;
  728. }
  729. /**
  730. * Add an external sub-select to the query.
  731. *
  732. * @param string $column
  733. * @param \Illuminate\Database\Query\Builder|static $query
  734. * @param string $boolean
  735. * @param bool $not
  736. * @return $this
  737. */
  738. protected function whereInExistingQuery($column, $query, $boolean, $not)
  739. {
  740. $type = $not ? 'NotInSub' : 'InSub';
  741. $this->wheres[] = compact('type', 'column', 'query', 'boolean');
  742. $this->addBinding($query->getBindings(), 'where');
  743. return $this;
  744. }
  745. /**
  746. * Add a "where null" clause to the query.
  747. *
  748. * @param string $column
  749. * @param string $boolean
  750. * @param bool $not
  751. * @return $this
  752. */
  753. public function whereNull($column, $boolean = 'and', $not = false)
  754. {
  755. $type = $not ? 'NotNull' : 'Null';
  756. $this->wheres[] = compact('type', 'column', 'boolean');
  757. return $this;
  758. }
  759. /**
  760. * Add an "or where null" clause to the query.
  761. *
  762. * @param string $column
  763. * @return \Illuminate\Database\Query\Builder|static
  764. */
  765. public function orWhereNull($column)
  766. {
  767. return $this->whereNull($column, 'or');
  768. }
  769. /**
  770. * Add a "where not null" clause to the query.
  771. *
  772. * @param string $column
  773. * @param string $boolean
  774. * @return \Illuminate\Database\Query\Builder|static
  775. */
  776. public function whereNotNull($column, $boolean = 'and')
  777. {
  778. return $this->whereNull($column, $boolean, true);
  779. }
  780. /**
  781. * Add a where between statement to the query.
  782. *
  783. * @param string $column
  784. * @param array $values
  785. * @param string $boolean
  786. * @param bool $not
  787. * @return $this
  788. */
  789. public function whereBetween($column, array $values, $boolean = 'and', $not = false)
  790. {
  791. $type = 'between';
  792. $this->wheres[] = compact('column', 'type', 'boolean', 'not');
  793. $this->addBinding($values, 'where');
  794. return $this;
  795. }
  796. /**
  797. * Add an or where between statement to the query.
  798. *
  799. * @param string $column
  800. * @param array $values
  801. * @return \Illuminate\Database\Query\Builder|static
  802. */
  803. public function orWhereBetween($column, array $values)
  804. {
  805. return $this->whereBetween($column, $values, 'or');
  806. }
  807. /**
  808. * Add a where not between statement to the query.
  809. *
  810. * @param string $column
  811. * @param array $values
  812. * @param string $boolean
  813. * @return \Illuminate\Database\Query\Builder|static
  814. */
  815. public function whereNotBetween($column, array $values, $boolean = 'and')
  816. {
  817. return $this->whereBetween($column, $values, $boolean, true);
  818. }
  819. /**
  820. * Add an or where not between statement to the query.
  821. *
  822. * @param string $column
  823. * @param array $values
  824. * @return \Illuminate\Database\Query\Builder|static
  825. */
  826. public function orWhereNotBetween($column, array $values)
  827. {
  828. return $this->whereNotBetween($column, $values, 'or');
  829. }
  830. /**
  831. * Add an "or where not null" clause to the query.
  832. *
  833. * @param string $column
  834. * @return \Illuminate\Database\Query\Builder|static
  835. */
  836. public function orWhereNotNull($column)
  837. {
  838. return $this->whereNotNull($column, 'or');
  839. }
  840. /**
  841. * Add a "where date" statement to the query.
  842. *
  843. * @param string $column
  844. * @param string $operator
  845. * @param mixed $value
  846. * @param string $boolean
  847. * @return \Illuminate\Database\Query\Builder|static
  848. */
  849. public function whereDate($column, $operator, $value = null, $boolean = 'and')
  850. {
  851. list($value, $operator) = $this->prepareValueAndOperator(
  852. $value, $operator, func_num_args() == 2
  853. );
  854. return $this->addDateBasedWhere('Date', $column, $operator, $value, $boolean);
  855. }
  856. /**
  857. * Add an "or where date" statement to the query.
  858. *
  859. * @param string $column
  860. * @param string $operator
  861. * @param string $value
  862. * @return \Illuminate\Database\Query\Builder|static
  863. */
  864. public function orWhereDate($column, $operator, $value)
  865. {
  866. list($value, $operator) = $this->prepareValueAndOperator(
  867. $value, $operator, func_num_args() == 2
  868. );
  869. return $this->whereDate($column, $operator, $value, 'or');
  870. }
  871. /**
  872. * Add a "where time" statement to the query.
  873. *
  874. * @param string $column
  875. * @param string $operator
  876. * @param int $value
  877. * @param string $boolean
  878. * @return \Illuminate\Database\Query\Builder|static
  879. */
  880. public function whereTime($column, $operator, $value, $boolean = 'and')
  881. {
  882. return $this->addDateBasedWhere('Time', $column, $operator, $value, $boolean);
  883. }
  884. /**
  885. * Add an "or where time" statement to the query.
  886. *
  887. * @param string $column
  888. * @param string $operator
  889. * @param int $value
  890. * @return \Illuminate\Database\Query\Builder|static
  891. */
  892. public function orWhereTime($column, $operator, $value)
  893. {
  894. list($value, $operator) = $this->prepareValueAndOperator(
  895. $value, $operator, func_num_args() == 2
  896. );
  897. return $this->whereTime($column, $operator, $value, 'or');
  898. }
  899. /**
  900. * Add a "where day" statement to the query.
  901. *
  902. * @param string $column
  903. * @param string $operator
  904. * @param mixed $value
  905. * @param string $boolean
  906. * @return \Illuminate\Database\Query\Builder|static
  907. */
  908. public function whereDay($column, $operator, $value = null, $boolean = 'and')
  909. {
  910. list($value, $operator) = $this->prepareValueAndOperator(
  911. $value, $operator, func_num_args() == 2
  912. );
  913. return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean);
  914. }
  915. /**
  916. * Add a "where month" statement to the query.
  917. *
  918. * @param string $column
  919. * @param string $operator
  920. * @param mixed $value
  921. * @param string $boolean
  922. * @return \Illuminate\Database\Query\Builder|static
  923. */
  924. public function whereMonth($column, $operator, $value = null, $boolean = 'and')
  925. {
  926. list($value, $operator) = $this->prepareValueAndOperator(
  927. $value, $operator, func_num_args() == 2
  928. );
  929. return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean);
  930. }
  931. /**
  932. * Add a "where year" statement to the query.
  933. *
  934. * @param string $column
  935. * @param string $operator
  936. * @param mixed $value
  937. * @param string $boolean
  938. * @return \Illuminate\Database\Query\Builder|static
  939. */
  940. public function whereYear($column, $operator, $value = null, $boolean = 'and')
  941. {
  942. list($value, $operator) = $this->prepareValueAndOperator(
  943. $value, $operator, func_num_args() == 2
  944. );
  945. return $this->addDateBasedWhere('Year', $column, $operator, $value, $boolean);
  946. }
  947. /**
  948. * Add a date based (year, month, day, time) statement to the query.
  949. *
  950. * @param string $type
  951. * @param string $column
  952. * @param string $operator
  953. * @param int $value
  954. * @param string $boolean
  955. * @return $this
  956. */
  957. protected function addDateBasedWhere($type, $column, $operator, $value, $boolean = 'and')
  958. {
  959. $this->wheres[] = compact('column', 'type', 'boolean', 'operator', 'value');
  960. if (! $value instanceof Expression) {
  961. $this->addBinding($value, 'where');
  962. }
  963. return $this;
  964. }
  965. /**
  966. * Add a nested where statement to the query.
  967. *
  968. * @param \Closure $callback
  969. * @param string $boolean
  970. * @return \Illuminate\Database\Query\Builder|static
  971. */
  972. public function whereNested(Closure $callback, $boolean = 'and')
  973. {
  974. call_user_func($callback, $query = $this->forNestedWhere());
  975. return $this->addNestedWhereQuery($query, $boolean);
  976. }
  977. /**
  978. * Create a new query instance for nested where condition.
  979. *
  980. * @return \Illuminate\Database\Query\Builder
  981. */
  982. public function forNestedWhere()
  983. {
  984. return $this->newQuery()->from($this->from);
  985. }
  986. /**
  987. * Add another query builder as a nested where to the query builder.
  988. *
  989. * @param \Illuminate\Database\Query\Builder|static $query
  990. * @param string $boolean
  991. * @return $this
  992. */
  993. public function addNestedWhereQuery($query, $boolean = 'and')
  994. {
  995. if (count($query->wheres)) {
  996. $type = 'Nested';
  997. $this->wheres[] = compact('type', 'query', 'boolean');
  998. $this->addBinding($query->getBindings(), 'where');
  999. }
  1000. return $this;
  1001. }
  1002. /**
  1003. * Add a full sub-select to the query.
  1004. *
  1005. * @param string $column
  1006. * @param string $operator
  1007. * @param \Closure $callback
  1008. * @param string $boolean
  1009. * @return $this
  1010. */
  1011. protected function whereSub($column, $operator, Closure $callback, $boolean)
  1012. {
  1013. $type = 'Sub';
  1014. // Once we have the query instance we can simply execute it so it can add all
  1015. // of the sub-select's conditions to itself, and then we can cache it off
  1016. // in the array of where clauses for the "main" parent query instance.
  1017. call_user_func($callback, $query = $this->forSubQuery());
  1018. $this->wheres[] = compact(
  1019. 'type', 'column', 'operator', 'query', 'boolean'
  1020. );
  1021. $this->addBinding($query->getBindings(), 'where');
  1022. return $this;
  1023. }
  1024. /**
  1025. * Add an exists clause to the query.
  1026. *
  1027. * @param \Closure $callback
  1028. * @param string $boolean
  1029. * @param bool $not
  1030. * @return $this
  1031. */
  1032. public function whereExists(Closure $callback, $boolean = 'and', $not = false)
  1033. {
  1034. $query = $this->forSubQuery();
  1035. // Similar to the sub-select clause, we will create a new query instance so
  1036. // the developer may cleanly specify the entire exists query and we will
  1037. // compile the whole thing in the grammar and insert it into the SQL.
  1038. call_user_func($callback, $query);
  1039. return $this->addWhereExistsQuery($query, $boolean, $not);
  1040. }
  1041. /**
  1042. * Add an or exists clause to the query.
  1043. *
  1044. * @param \Closure $callback
  1045. * @param bool $not
  1046. * @return \Illuminate\Database\Query\Builder|static
  1047. */
  1048. public function orWhereExists(Closure $callback, $not = false)
  1049. {
  1050. return $this->whereExists($callback, 'or', $not);
  1051. }
  1052. /**
  1053. * Add a where not exists clause to the query.
  1054. *
  1055. * @param \Closure $callback
  1056. * @param string $boolean
  1057. * @return \Illuminate\Database\Query\Builder|static
  1058. */
  1059. public function whereNotExists(Closure $callback, $boolean = 'and')
  1060. {
  1061. return $this->whereExists($callback, $boolean, true);
  1062. }
  1063. /**
  1064. * Add a where not exists clause to the query.
  1065. *
  1066. * @param \Closure $callback
  1067. * @return \Illuminate\Database\Query\Builder|static
  1068. */
  1069. public function orWhereNotExists(Closure $callback)
  1070. {
  1071. return $this->orWhereExists($callback, true);
  1072. }
  1073. /**
  1074. * Add an exists clause to the query.
  1075. *
  1076. * @param \Illuminate\Database\Query\Builder $query
  1077. * @param string $boolean
  1078. * @param bool $not
  1079. * @return $this
  1080. */
  1081. public function addWhereExistsQuery(self $query, $boolean = 'and', $not = false)
  1082. {
  1083. $type = $not ? 'NotExists' : 'Exists';
  1084. $this->wheres[] = compact('type', 'operator', 'query', 'boolean');
  1085. $this->addBinding($query->getBindings(), 'where');
  1086. return $this;
  1087. }
  1088. /**
  1089. * Handles dynamic "where" clauses to the query.
  1090. *
  1091. * @param string $method
  1092. * @param string $parameters
  1093. * @return $this
  1094. */
  1095. public function dynamicWhere($method, $parameters)
  1096. {
  1097. $finder = substr($method, 5);
  1098. $segments = preg_split(
  1099. '/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE
  1100. );
  1101. // The connector variable will determine which connector will be used for the
  1102. // query condition. We will change it as we come across new boolean values
  1103. // in the dynamic method strings, which could contain a number of these.
  1104. $connector = 'and';
  1105. $index = 0;
  1106. foreach ($segments as $segment) {
  1107. // If the segment is not a boolean connector, we can assume it is a column's name
  1108. // and we will add it to the query as a new constraint as a where clause, then
  1109. // we can keep iterating through the dynamic method string's segments again.
  1110. if ($segment !== 'And' && $segment !== 'Or') {
  1111. $this->addDynamic($segment, $connector, $parameters, $index);
  1112. $index++;
  1113. }
  1114. // Otherwise, we will store the connector so we know how the next where clause we
  1115. // find in the query should be connected to the previous ones, meaning we will
  1116. // have the proper boolean connector to connect the next where clause found.
  1117. else {
  1118. $connector = $segment;
  1119. }
  1120. }
  1121. return $this;
  1122. }
  1123. /**
  1124. * Add a single dynamic where clause statement to the query.
  1125. *
  1126. * @param string $segment
  1127. * @param string $connector
  1128. * @param array $parameters
  1129. * @param int $index
  1130. * @return void
  1131. */
  1132. protected function addDynamic($segment, $connector, $parameters, $index)
  1133. {
  1134. // Once we have parsed out the columns and formatted the boolean operators we
  1135. // are ready to add it to this query as a where clause just like any other
  1136. // clause on the query. Then we'll increment the parameter index values.
  1137. $bool = strtolower($connector);
  1138. $this->where(Str::snake($segment), '=', $parameters[$index], $bool);
  1139. }
  1140. /**
  1141. * Add a "group by" clause to the query.
  1142. *
  1143. * @param array ...$groups
  1144. * @return $this
  1145. */
  1146. public function groupBy(...$groups)
  1147. {
  1148. foreach ($groups as $group) {
  1149. $this->groups = array_merge(
  1150. (array) $this->groups,
  1151. Arr::wrap($group)
  1152. );
  1153. }
  1154. return $this;
  1155. }
  1156. /**
  1157. * Add a "having" clause to the query.
  1158. *
  1159. * @param string $column
  1160. * @param string|null $operator
  1161. * @param string|null $value
  1162. * @param string $boolean
  1163. * @return $this
  1164. */
  1165. public function having($column, $operator = null, $value = null, $boolean = 'and')
  1166. {
  1167. $type = 'Basic';
  1168. // Here we will make some assumptions about the operator. If only 2 values are
  1169. // passed to the method, we will assume that the operator is an equals sign
  1170. // and keep going. Otherwise, we'll require the operator to be passed in.
  1171. list($value, $operator) = $this->prepareValueAndOperator(
  1172. $value, $operator, func_num_args() == 2
  1173. );
  1174. // If the given operator is not found in the list of valid operators we will
  1175. // assume that the developer is just short-cutting the '=' operators and
  1176. // we will set the operators to '=' and set the values appropriately.
  1177. if ($this->invalidOperator($operator)) {
  1178. list($value, $operator) = [$operator, '='];
  1179. }
  1180. $this->havings[] = compact('type', 'column', 'operator', 'value', 'boolean');
  1181. if (! $value instanceof Expression) {
  1182. $this->addBinding($value, 'having');
  1183. }
  1184. return $this;
  1185. }
  1186. /**
  1187. * Add a "or having" clause to the query.
  1188. *
  1189. * @param string $column
  1190. * @param string|null $operator
  1191. * @param string|null $value
  1192. * @return \Illuminate\Database\Query\Builder|static
  1193. */
  1194. public function orHaving($column, $operator = null, $value = null)
  1195. {
  1196. return $this->having($column, $operator, $value, 'or');
  1197. }
  1198. /**
  1199. * Add a raw having clause to the query.
  1200. *
  1201. * @param string $sql
  1202. * @param array $bindings
  1203. * @param string $boolean
  1204. * @return $this
  1205. */
  1206. public function havingRaw($sql, array $bindings = [], $boolean = 'and')
  1207. {
  1208. $type = 'Raw';
  1209. $this->havings[] = compact('type', 'sql', 'boolean');
  1210. $this->addBinding($bindings, 'having');
  1211. return $this;
  1212. }
  1213. /**
  1214. * Add a raw or having clause to the query.
  1215. *
  1216. * @param string $sql
  1217. * @param array $bindings
  1218. * @return \Illuminate\Database\Query\Builder|static
  1219. */
  1220. public function orHavingRaw($sql, array $bindings = [])
  1221. {
  1222. return $this->havingRaw($sql, $bindings, 'or');
  1223. }
  1224. /**
  1225. * Add an "order by" clause to the query.
  1226. *
  1227. * @param string $column
  1228. * @param string $direction
  1229. * @return $this
  1230. */
  1231. public function orderBy($column, $direction = 'asc')
  1232. {
  1233. $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [
  1234. 'column' => $column,
  1235. 'direction' => strtolower($direction) == 'asc' ? 'asc' : 'desc',
  1236. ];
  1237. return $this;
  1238. }
  1239. /**
  1240. * Add a descending "order by" clause to the query.
  1241. *
  1242. * @param string $column
  1243. * @return $this
  1244. */
  1245. public function orderByDesc($column)
  1246. {
  1247. return $this->orderBy($column, 'desc');
  1248. }
  1249. /**
  1250. * Add an "order by" clause for a timestamp to the query.
  1251. *
  1252. * @param string $column
  1253. * @return \Illuminate\Database\Query\Builder|static
  1254. */
  1255. public function latest($column = 'created_at')
  1256. {
  1257. return $this->orderBy($column, 'desc');
  1258. }
  1259. /**
  1260. * Add an "order by" clause for a timestamp to the query.
  1261. *
  1262. * @param string $column
  1263. * @return \Illuminate\Database\Query\Builder|static
  1264. */
  1265. public function oldest($column = 'created_at')
  1266. {
  1267. return $this->orderBy($column, 'asc');
  1268. }
  1269. /**
  1270. * Put the query's results in random order.
  1271. *
  1272. * @param string $seed
  1273. * @return $this
  1274. */
  1275. public function inRandomOrder($seed = '')
  1276. {
  1277. return $this->orderByRaw($this->grammar->compileRandom($seed));
  1278. }
  1279. /**
  1280. * Add a raw "order by" clause to the query.
  1281. *
  1282. * @param string $sql
  1283. * @param array $bindings
  1284. * @return $this
  1285. */
  1286. public function orderByRaw($sql, $bindings = [])
  1287. {
  1288. $type = 'Raw';
  1289. $this->{$this->unions ? 'unionOrders' : 'orders'}[] = compact('type', 'sql');
  1290. $this->addBinding($bindings, 'order');
  1291. return $this;
  1292. }
  1293. /**
  1294. * Alias to set the "offset" value of the query.
  1295. *
  1296. * @param int $value
  1297. * @return \Illuminate\Database\Query\Builder|static
  1298. */
  1299. public function skip($value)
  1300. {
  1301. return $this->offset($value);
  1302. }
  1303. /**
  1304. * Set the "offset" value of the query.
  1305. *
  1306. * @param int $value
  1307. * @return $this
  1308. */
  1309. public function offset($value)
  1310. {
  1311. $property = $this->unions ? 'unionOffset' : 'offset';
  1312. $this->$property = max(0, $value);
  1313. return $this;
  1314. }
  1315. /**
  1316. * Alias to set the "limit" value of the query.
  1317. *
  1318. * @param int $value
  1319. * @return \Illuminate\Database\Query\Builder|static
  1320. */
  1321. public function take($value)
  1322. {
  1323. return $this->limit($value);
  1324. }
  1325. /**
  1326. * Set the "limit" value of the query.
  1327. *
  1328. * @param int $value
  1329. * @return $this
  1330. */
  1331. public function limit($value)
  1332. {
  1333. $property = $this->unions ? 'unionLimit' : 'limit';
  1334. if ($value >= 0) {
  1335. $this->$property = $value;
  1336. }
  1337. return $this;
  1338. }
  1339. /**
  1340. * Set the limit and offset for a given page.
  1341. *
  1342. * @param int $page
  1343. * @param int $perPage
  1344. * @return \Illuminate\Database\Query\Builder|static
  1345. */
  1346. public function forPage($page, $perPage = 15)
  1347. {
  1348. return $this->skip(($page - 1) * $perPage)->take($perPage);
  1349. }
  1350. /**
  1351. * Constrain the query to the next "page" of results after a given ID.
  1352. *
  1353. * @param int $perPage
  1354. * @param int $lastId
  1355. * @param string $column
  1356. * @return \Illuminate\Database\Query\Builder|static
  1357. */
  1358. public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id')
  1359. {
  1360. $this->orders = $this->removeExistingOrdersFor($column);
  1361. return $this->where($column, '>', $lastId)
  1362. ->orderBy($column, 'asc')
  1363. ->take($perPage);
  1364. }
  1365. /**
  1366. * Get an array with all orders with a given column removed.
  1367. *
  1368. * @param string $column
  1369. * @return array
  1370. */
  1371. protected function removeExistingOrdersFor($column)
  1372. {
  1373. return Collection::make($this->orders)
  1374. ->reject(function ($order) use ($column) {
  1375. return isset($order['column'])
  1376. ? $order['column'] === $column : false;
  1377. })->values()->all();
  1378. }
  1379. /**
  1380. * Add a union statement to the query.
  1381. *
  1382. * @param \Illuminate\Database\Query\Builder|\Closure $query
  1383. * @param bool $all
  1384. * @return \Illuminate\Database\Query\Builder|static
  1385. */
  1386. public function union($query, $all = false)
  1387. {
  1388. if ($query instanceof Closure) {
  1389. call_user_func($query, $query = $this->newQuery());
  1390. }
  1391. $this->unions[] = compact('query', 'all');
  1392. $this->addBinding($query->getBindings(), 'union');
  1393. return $this;
  1394. }
  1395. /**
  1396. * Add a union all statement to the query.
  1397. *
  1398. * @param \Illuminate\Database\Query\Builder|\Closure $query
  1399. * @return \Illuminate\Database\Query\Builder|static
  1400. */
  1401. public function unionAll($query)
  1402. {
  1403. return $this->union($query, true);
  1404. }
  1405. /**
  1406. * Lock the selected rows in the table.
  1407. *
  1408. * @param string|bool $value
  1409. * @return $this
  1410. */
  1411. public function lock($value = true)
  1412. {
  1413. $this->lock = $value;
  1414. if (! is_null($this->lock)) {
  1415. $this->useWritePdo();
  1416. }
  1417. return $this;
  1418. }
  1419. /**
  1420. * Lock the selected rows in the table for updating.
  1421. *
  1422. * @return \Illuminate\Database\Query\Builder
  1423. */
  1424. public function lockForUpdate()
  1425. {
  1426. return $this->lock(true);
  1427. }
  1428. /**
  1429. * Share lock the selected rows in the table.
  1430. *
  1431. * @return \Illuminate\Database\Query\Builder
  1432. */
  1433. public function sharedLock()
  1434. {
  1435. return $this->lock(false);
  1436. }
  1437. /**
  1438. * Get the SQL representation of the query.
  1439. *
  1440. * @return string
  1441. */
  1442. public function toSql()
  1443. {
  1444. return $this->grammar->compileSelect($this);
  1445. }
  1446. /**
  1447. * Execute a query for a single record by ID.
  1448. *
  1449. * @param int $id
  1450. * @param array $columns
  1451. * @return mixed|static
  1452. */
  1453. public function find($id, $columns = ['*'])
  1454. {
  1455. return $this->where('id', '=', $id)->first($columns);
  1456. }
  1457. /**
  1458. * Get a single column's value from the first result of a query.
  1459. *
  1460. * @param string $column
  1461. * @return mixed
  1462. */
  1463. public function value($column)
  1464. {
  1465. $result = (array) $this->first([$column]);
  1466. return count($result) > 0 ? reset($result) : null;
  1467. }
  1468. /**
  1469. * Execute the query as a "select" statement.
  1470. *
  1471. * @param array $columns
  1472. * @return \Illuminate\Support\Collection
  1473. */
  1474. public function get($columns = ['*'])
  1475. {
  1476. $original = $this->columns;
  1477. if (is_null($original)) {
  1478. $this->columns = $columns;
  1479. }
  1480. $results = $this->processor->processSelect($this, $this->runSelect());
  1481. $this->columns = $original;
  1482. return collect($results);
  1483. }
  1484. /**
  1485. * Run the query as a "select" statement against the connection.
  1486. *
  1487. * @return array
  1488. */
  1489. protected function runSelect()
  1490. {
  1491. return $this->connection->select(
  1492. $this->toSql(), $this->getBindings(), ! $this->useWritePdo
  1493. );
  1494. }
  1495. /**
  1496. * Paginate the given query into a simple paginator.
  1497. *
  1498. * @param int $perPage
  1499. * @param array $columns
  1500. * @param string $pageName
  1501. * @param int|null $page
  1502. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1503. */
  1504. public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null)
  1505. {
  1506. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  1507. $total = $this->getCountForPagination($columns);
  1508. $results = $total ? $this->forPage($page, $perPage)->get($columns) : collect();
  1509. return $this->paginator($results, $total, $perPage, $page, [
  1510. 'path' => Paginator::resolveCurrentPath(),
  1511. 'pageName' => $pageName,
  1512. ]);
  1513. }
  1514. /**
  1515. * Get a paginator only supporting simple next and previous links.
  1516. *
  1517. * This is more efficient on larger data-sets, etc.
  1518. *
  1519. * @param int $perPage
  1520. * @param array $columns
  1521. * @param string $pageName
  1522. * @param int|null $page
  1523. * @return \Illuminate\Contracts\Pagination\Paginator
  1524. */
  1525. public function simplePaginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null)
  1526. {
  1527. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  1528. $this->skip(($page - 1) * $perPage)->take($perPage + 1);
  1529. return $this->simplePaginator($this->get($columns), $perPage, $page, [
  1530. 'path' => Paginator::resolveCurrentPath(),
  1531. 'pageName' => $pageName,
  1532. ]);
  1533. }
  1534. /**
  1535. * Get the count of the total records for the paginator.
  1536. *
  1537. * @param array $columns
  1538. * @return int
  1539. */
  1540. public function getCountForPagination($columns = ['*'])
  1541. {
  1542. $results = $this->runPaginationCountQuery($columns);
  1543. // Once we have run the pagination count query, we will get the resulting count and
  1544. // take into account what type of query it was. When there is a group by we will
  1545. // just return the count of the entire results set since that will be correct.
  1546. if (isset($this->groups)) {
  1547. return count($results);
  1548. } elseif (! isset($results[0])) {
  1549. return 0;
  1550. } elseif (is_object($results[0])) {
  1551. return (int) $results[0]->aggregate;
  1552. }
  1553. return (int) array_change_key_case((array) $results[0])['aggregate'];
  1554. }
  1555. /**
  1556. * Run a pagination count query.
  1557. *
  1558. * @param array $columns
  1559. * @return array
  1560. */
  1561. protected function runPaginationCountQuery($columns = ['*'])
  1562. {
  1563. return $this->cloneWithout(['columns', 'orders', 'limit', 'offset'])
  1564. ->cloneWithoutBindings(['select', 'order'])
  1565. ->setAggregate('count', $this->withoutSelectAliases($columns))
  1566. ->get()->all();
  1567. }
  1568. /**
  1569. * Remove the column aliases since they will break count queries.
  1570. *
  1571. * @param array $columns
  1572. * @return array
  1573. */
  1574. protected function withoutSelectAliases(array $columns)
  1575. {
  1576. return array_map(function ($column) {
  1577. return is_string($column) && ($aliasPosition = strpos(strtolower($column), ' as ')) !== false
  1578. ? substr($column, 0, $aliasPosition) : $column;
  1579. }, $columns);
  1580. }
  1581. /**
  1582. * Get a generator for the given query.
  1583. *
  1584. * @return \Generator
  1585. */
  1586. public function cursor()
  1587. {
  1588. if (is_null($this->columns)) {
  1589. $this->columns = ['*'];
  1590. }
  1591. return $this->connection->cursor(
  1592. $this->toSql(), $this->getBindings(), ! $this->useWritePdo
  1593. );
  1594. }
  1595. /**
  1596. * Chunk the results of a query by comparing numeric IDs.
  1597. *
  1598. * @param int $count
  1599. * @param callable $callback
  1600. * @param string $column
  1601. * @param string $alias
  1602. * @return bool
  1603. */
  1604. public function chunkById($count, callable $callback, $column = 'id', $alias = null)
  1605. {
  1606. $alias = $alias ?: $column;
  1607. $lastId = 0;
  1608. do {
  1609. $clone = clone $this;
  1610. // We'll execute the query for the given page and get the results. If there are
  1611. // no results we can just break and return from here. When there are results
  1612. // we will call the callback with the current chunk of these results here.
  1613. $results = $clone->forPageAfterId($count, $lastId, $column)->get();
  1614. $countResults = $results->count();
  1615. if ($countResults == 0) {
  1616. break;
  1617. }
  1618. // On each chunk result set, we will pass them to the callback and then let the
  1619. // developer take care of everything within the callback, which allows us to
  1620. // keep the memory low for spinning through large result sets for working.
  1621. if ($callback($results) === false) {
  1622. return false;
  1623. }
  1624. $lastId = $results->last()->{$alias};
  1625. unset($results);
  1626. } while ($countResults == $count);
  1627. return true;
  1628. }
  1629. /**
  1630. * Throw an exception if the query doesn't have an orderBy clause.
  1631. *
  1632. * @return void
  1633. *
  1634. * @throws \RuntimeException
  1635. */
  1636. protected function enforceOrderBy()
  1637. {
  1638. if (empty($this->orders) && empty($this->unionOrders)) {
  1639. throw new RuntimeException('You must specify an orderBy clause when using this function.');
  1640. }
  1641. }
  1642. /**
  1643. * Get an array with the values of a given column.
  1644. *
  1645. * @param string $column
  1646. * @param string|null $key
  1647. * @return \Illuminate\Support\Collection
  1648. */
  1649. public function pluck($column, $key = null)
  1650. {
  1651. $results = $this->get(is_null($key) ? [$column] : [$column, $key]);
  1652. // If the columns are qualified with a table or have an alias, we cannot use
  1653. // those directly in the "pluck" operations since the results from the DB
  1654. // are only keyed by the column itself. We'll strip the table out here.
  1655. return $results->pluck(
  1656. $this->stripTableForPluck($column),
  1657. $this->stripTableForPluck($key)
  1658. );
  1659. }
  1660. /**
  1661. * Strip off the table name or alias from a column identifier.
  1662. *
  1663. * @param string $column
  1664. * @return string|null
  1665. */
  1666. protected function stripTableForPluck($column)
  1667. {
  1668. return is_null($column) ? $column : last(preg_split('~\.| ~', $column));
  1669. }
  1670. /**
  1671. * Concatenate values of a given column as a string.
  1672. *
  1673. * @param string $column
  1674. * @param string $glue
  1675. * @return string
  1676. */
  1677. public function implode($column, $glue = '')
  1678. {
  1679. return $this->pluck($column)->implode($glue);
  1680. }
  1681. /**
  1682. * Determine if any rows exist for the current query.
  1683. *
  1684. * @return bool
  1685. */
  1686. public function exists()
  1687. {
  1688. $results = $this->connection->select(
  1689. $this->grammar->compileExists($this), $this->getBindings(), ! $this->useWritePdo
  1690. );
  1691. // If the results has rows, we will get the row and see if the exists column is a
  1692. // boolean true. If there is no results for this query we will return false as
  1693. // there are no rows for this query at all and we can return that info here.
  1694. if (isset($results[0])) {
  1695. $results = (array) $results[0];
  1696. return (bool) $results['exists'];
  1697. }
  1698. return false;
  1699. }
  1700. /**
  1701. * Determine if no rows exist for the current query.
  1702. *
  1703. * @return bool
  1704. */
  1705. public function doesntExist()
  1706. {
  1707. return ! $this->exists();
  1708. }
  1709. /**
  1710. * Retrieve the "count" result of the query.
  1711. *
  1712. * @param string $columns
  1713. * @return int
  1714. */
  1715. public function count($columns = '*')
  1716. {
  1717. return (int) $this->aggregate(__FUNCTION__, Arr::wrap($columns));
  1718. }
  1719. /**
  1720. * Retrieve the minimum value of a given column.
  1721. *
  1722. * @param string $column
  1723. * @return mixed
  1724. */
  1725. public function min($column)
  1726. {
  1727. return $this->aggregate(__FUNCTION__, [$column]);
  1728. }
  1729. /**
  1730. * Retrieve the maximum value of a given column.
  1731. *
  1732. * @param string $column
  1733. * @return mixed
  1734. */
  1735. public function max($column)
  1736. {
  1737. return $this->aggregate(__FUNCTION__, [$column]);
  1738. }
  1739. /**
  1740. * Retrieve the sum of the values of a given column.
  1741. *
  1742. * @param string $column
  1743. * @return mixed
  1744. */
  1745. public function sum($column)
  1746. {
  1747. $result = $this->aggregate(__FUNCTION__, [$column]);
  1748. return $result ?: 0;
  1749. }
  1750. /**
  1751. * Retrieve the average of the values of a given column.
  1752. *
  1753. * @param string $column
  1754. * @return mixed
  1755. */
  1756. public function avg($column)
  1757. {
  1758. return $this->aggregate(__FUNCTION__, [$column]);
  1759. }
  1760. /**
  1761. * Alias for the "avg" method.
  1762. *
  1763. * @param string $column
  1764. * @return mixed
  1765. */
  1766. public function average($column)
  1767. {
  1768. return $this->avg($column);
  1769. }
  1770. /**
  1771. * Execute an aggregate function on the database.
  1772. *
  1773. * @param string $function
  1774. * @param array $columns
  1775. * @return mixed
  1776. */
  1777. public function aggregate($function, $columns = ['*'])
  1778. {
  1779. $results = $this->cloneWithout(['columns'])
  1780. ->cloneWithoutBindings(['select'])
  1781. ->setAggregate($function, $columns)
  1782. ->get($columns);
  1783. if (! $results->isEmpty()) {
  1784. return array_change_key_case((array) $results[0])['aggregate'];
  1785. }
  1786. }
  1787. /**
  1788. * Execute a numeric aggregate function on the database.
  1789. *
  1790. * @param string $function
  1791. * @param array $columns
  1792. * @return float|int
  1793. */
  1794. public function numericAggregate($function, $columns = ['*'])
  1795. {
  1796. $result = $this->aggregate($function, $columns);
  1797. // If there is no result, we can obviously just return 0 here. Next, we will check
  1798. // if the result is an integer or float. If it is already one of these two data
  1799. // types we can just return the result as-is, otherwise we will convert this.
  1800. if (! $result) {
  1801. return 0;
  1802. }
  1803. if (is_int($result) || is_float($result)) {
  1804. return $result;
  1805. }
  1806. // If the result doesn't contain a decimal place, we will assume it is an int then
  1807. // cast it to one. When it does we will cast it to a float since it needs to be
  1808. // cast to the expected data type for the developers out of pure convenience.
  1809. return strpos((string) $result, '.') === false
  1810. ? (int) $result : (float) $result;
  1811. }
  1812. /**
  1813. * Set the aggregate property without running the query.
  1814. *
  1815. * @param string $function
  1816. * @param array $columns
  1817. * @return $this
  1818. */
  1819. protected function setAggregate($function, $columns)
  1820. {
  1821. $this->aggregate = compact('function', 'columns');
  1822. if (empty($this->groups)) {
  1823. $this->orders = null;
  1824. $this->bindings['order'] = [];
  1825. }
  1826. return $this;
  1827. }
  1828. /**
  1829. * Insert a new record into the database.
  1830. *
  1831. * @param array $values
  1832. * @return bool
  1833. */
  1834. public function insert(array $values)
  1835. {
  1836. // Since every insert gets treated like a batch insert, we will make sure the
  1837. // bindings are structured in a way that is convenient when building these
  1838. // inserts statements by verifying these elements are actually an array.
  1839. if (empty($values)) {
  1840. return true;
  1841. }
  1842. if (! is_array(reset($values))) {
  1843. $values = [$values];
  1844. }
  1845. // Here, we will sort the insert keys for every record so that each insert is
  1846. // in the same order for the record. We need to make sure this is the case
  1847. // so there are not any errors or problems when inserting these records.
  1848. else {
  1849. foreach ($values as $key => $value) {
  1850. ksort($value);
  1851. $values[$key] = $value;
  1852. }
  1853. }
  1854. // Finally, we will run this query against the database connection and return
  1855. // the results. We will need to also flatten these bindings before running
  1856. // the query so they are all in one huge, flattened array for execution.
  1857. return $this->connection->insert(
  1858. $this->grammar->compileInsert($this, $values),
  1859. $this->cleanBindings(Arr::flatten($values, 1))
  1860. );
  1861. }
  1862. /**
  1863. * Insert a new record and get the value of the primary key.
  1864. *
  1865. * @param array $values
  1866. * @param string|null $sequence
  1867. * @return int
  1868. */
  1869. public function insertGetId(array $values, $sequence = null)
  1870. {
  1871. $sql = $this->grammar->compileInsertGetId($this, $values, $sequence);
  1872. $values = $this->cleanBindings($values);
  1873. return $this->processor->processInsertGetId($this, $sql, $values, $sequence);
  1874. }
  1875. /**
  1876. * Update a record in the database.
  1877. *
  1878. * @param array $values
  1879. * @return int
  1880. */
  1881. public function update(array $values)
  1882. {
  1883. $sql = $this->grammar->compileUpdate($this, $values);
  1884. return $this->connection->update($sql, $this->cleanBindings(
  1885. $this->grammar->prepareBindingsForUpdate($this->bindings, $values)
  1886. ));
  1887. }
  1888. /**
  1889. * Insert or update a record matching the attributes, and fill it with values.
  1890. *
  1891. * @param array $attributes
  1892. * @param array $values
  1893. * @return bool
  1894. */
  1895. public function updateOrInsert(array $attributes, array $values = [])
  1896. {
  1897. if (! $this->where($attributes)->exists()) {
  1898. return $this->insert(array_merge($attributes, $values));
  1899. }
  1900. return (bool) $this->take(1)->update($values);
  1901. }
  1902. /**
  1903. * Increment a column's value by a given amount.
  1904. *
  1905. * @param string $column
  1906. * @param int $amount
  1907. * @param array $extra
  1908. * @return int
  1909. */
  1910. public function increment($column, $amount = 1, array $extra = [])
  1911. {
  1912. if (! is_numeric($amount)) {
  1913. throw new InvalidArgumentException('Non-numeric value passed to increment method.');
  1914. }
  1915. $wrapped = $this->grammar->wrap($column);
  1916. $columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra);
  1917. return $this->update($columns);
  1918. }
  1919. /**
  1920. * Decrement a column's value by a given amount.
  1921. *
  1922. * @param string $column
  1923. * @param int $amount
  1924. * @param array $extra
  1925. * @return int
  1926. */
  1927. public function decrement($column, $amount = 1, array $extra = [])
  1928. {
  1929. if (! is_numeric($amount)) {
  1930. throw new InvalidArgumentException('Non-numeric value passed to decrement method.');
  1931. }
  1932. $wrapped = $this->grammar->wrap($column);
  1933. $columns = array_merge([$column => $this->raw("$wrapped - $amount")], $extra);
  1934. return $this->update($columns);
  1935. }
  1936. /**
  1937. * Delete a record from the database.
  1938. *
  1939. * @param mixed $id
  1940. * @return int
  1941. */
  1942. public function delete($id = null)
  1943. {
  1944. // If an ID is passed to the method, we will set the where clause to check the
  1945. // ID to let developers to simply and quickly remove a single row from this
  1946. // database without manually specifying the "where" clauses on the query.
  1947. if (! is_null($id)) {
  1948. $this->where($this->from.'.id', '=', $id);
  1949. }
  1950. return $this->connection->delete(
  1951. $this->grammar->compileDelete($this), $this->cleanBindings(
  1952. $this->grammar->prepareBindingsForDelete($this->bindings)
  1953. )
  1954. );
  1955. }
  1956. /**
  1957. * Run a truncate statement on the table.
  1958. *
  1959. * @return void
  1960. */
  1961. public function truncate()
  1962. {
  1963. foreach ($this->grammar->compileTruncate($this) as $sql => $bindings) {
  1964. $this->connection->statement($sql, $bindings);
  1965. }
  1966. }
  1967. /**
  1968. * Get a new instance of the query builder.
  1969. *
  1970. * @return \Illuminate\Database\Query\Builder
  1971. */
  1972. public function newQuery()
  1973. {
  1974. return new static($this->connection, $this->grammar, $this->processor);
  1975. }
  1976. /**
  1977. * Create a new query instance for a sub-query.
  1978. *
  1979. * @return \Illuminate\Database\Query\Builder
  1980. */
  1981. protected function forSubQuery()
  1982. {
  1983. return $this->newQuery();
  1984. }
  1985. /**
  1986. * Create a raw database expression.
  1987. *
  1988. * @param mixed $value
  1989. * @return \Illuminate\Database\Query\Expression
  1990. */
  1991. public function raw($value)
  1992. {
  1993. return $this->connection->raw($value);
  1994. }
  1995. /**
  1996. * Get the current query value bindings in a flattened array.
  1997. *
  1998. * @return array
  1999. */
  2000. public function getBindings()
  2001. {
  2002. return Arr::flatten($this->bindings);
  2003. }
  2004. /**
  2005. * Get the raw array of bindings.
  2006. *
  2007. * @return array
  2008. */
  2009. public function getRawBindings()
  2010. {
  2011. return $this->bindings;
  2012. }
  2013. /**
  2014. * Set the bindings on the query builder.
  2015. *
  2016. * @param array $bindings
  2017. * @param string $type
  2018. * @return $this
  2019. *
  2020. * @throws \InvalidArgumentException
  2021. */
  2022. public function setBindings(array $bindings, $type = 'where')
  2023. {
  2024. if (! array_key_exists($type, $this->bindings)) {
  2025. throw new InvalidArgumentException("Invalid binding type: {$type}.");
  2026. }
  2027. $this->bindings[$type] = $bindings;
  2028. return $this;
  2029. }
  2030. /**
  2031. * Add a binding to the query.
  2032. *
  2033. * @param mixed $value
  2034. * @param string $type
  2035. * @return $this
  2036. *
  2037. * @throws \InvalidArgumentException
  2038. */
  2039. public function addBinding($value, $type = 'where')
  2040. {
  2041. if (! array_key_exists($type, $this->bindings)) {
  2042. throw new InvalidArgumentException("Invalid binding type: {$type}.");
  2043. }
  2044. if (is_array($value)) {
  2045. $this->bindings[$type] = array_values(array_merge($this->bindings[$type], $value));
  2046. } else {
  2047. $this->bindings[$type][] = $value;
  2048. }
  2049. return $this;
  2050. }
  2051. /**
  2052. * Merge an array of bindings into our bindings.
  2053. *
  2054. * @param \Illuminate\Database\Query\Builder $query
  2055. * @return $this
  2056. */
  2057. public function mergeBindings(self $query)
  2058. {
  2059. $this->bindings = array_merge_recursive($this->bindings, $query->bindings);
  2060. return $this;
  2061. }
  2062. /**
  2063. * Remove all of the expressions from a list of bindings.
  2064. *
  2065. * @param array $bindings
  2066. * @return array
  2067. */
  2068. protected function cleanBindings(array $bindings)
  2069. {
  2070. return array_values(array_filter($bindings, function ($binding) {
  2071. return ! $binding instanceof Expression;
  2072. }));
  2073. }
  2074. /**
  2075. * Get the database connection instance.
  2076. *
  2077. * @return \Illuminate\Database\ConnectionInterface
  2078. */
  2079. public function getConnection()
  2080. {
  2081. return $this->connection;
  2082. }
  2083. /**
  2084. * Get the database query processor instance.
  2085. *
  2086. * @return \Illuminate\Database\Query\Processors\Processor
  2087. */
  2088. public function getProcessor()
  2089. {
  2090. return $this->processor;
  2091. }
  2092. /**
  2093. * Get the query grammar instance.
  2094. *
  2095. * @return \Illuminate\Database\Query\Grammars\Grammar
  2096. */
  2097. public function getGrammar()
  2098. {
  2099. return $this->grammar;
  2100. }
  2101. /**
  2102. * Use the write pdo for query.
  2103. *
  2104. * @return $this
  2105. */
  2106. public function useWritePdo()
  2107. {
  2108. $this->useWritePdo = true;
  2109. return $this;
  2110. }
  2111. /**
  2112. * Clone the query without the given properties.
  2113. *
  2114. * @param array $properties
  2115. * @return static
  2116. */
  2117. public function cloneWithout(array $properties)
  2118. {
  2119. return tap(clone $this, function ($clone) use ($properties) {
  2120. foreach ($properties as $property) {
  2121. $clone->{$property} = null;
  2122. }
  2123. });
  2124. }
  2125. /**
  2126. * Clone the query without the given bindings.
  2127. *
  2128. * @param array $except
  2129. * @return static
  2130. */
  2131. public function cloneWithoutBindings(array $except)
  2132. {
  2133. return tap(clone $this, function ($clone) use ($except) {
  2134. foreach ($except as $type) {
  2135. $clone->bindings[$type] = [];
  2136. }
  2137. });
  2138. }
  2139. /**
  2140. * Handle dynamic method calls into the method.
  2141. *
  2142. * @param string $method
  2143. * @param array $parameters
  2144. * @return mixed
  2145. *
  2146. * @throws \BadMethodCallException
  2147. */
  2148. public function __call($method, $parameters)
  2149. {
  2150. if (static::hasMacro($method)) {
  2151. return $this->macroCall($method, $parameters);
  2152. }
  2153. if (Str::startsWith($method, 'where')) {
  2154. return $this->dynamicWhere($method, $parameters);
  2155. }
  2156. $className = static::class;
  2157. throw new BadMethodCallException("Call to undefined method {$className}::{$method}()");
  2158. }
  2159. }