Builder.php 84 KB

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