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

Builder.php 83KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998
  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', '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->wrap($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->wrap($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 $column
  870. * @param string $boolean
  871. * @param bool $not
  872. * @return $this
  873. */
  874. public function whereNull($column, $boolean = 'and', $not = false)
  875. {
  876. $type = $not ? 'NotNull' : 'Null';
  877. $this->wheres[] = compact('type', 'column', 'boolean');
  878. return $this;
  879. }
  880. /**
  881. * Add an "or where null" clause to the query.
  882. *
  883. * @param string $column
  884. * @return \Illuminate\Database\Query\Builder|static
  885. */
  886. public function orWhereNull($column)
  887. {
  888. return $this->whereNull($column, 'or');
  889. }
  890. /**
  891. * Add a "where not null" clause to the query.
  892. *
  893. * @param string $column
  894. * @param string $boolean
  895. * @return \Illuminate\Database\Query\Builder|static
  896. */
  897. public function whereNotNull($column, $boolean = 'and')
  898. {
  899. return $this->whereNull($column, $boolean, true);
  900. }
  901. /**
  902. * Add a where between statement to the query.
  903. *
  904. * @param string $column
  905. * @param array $values
  906. * @param string $boolean
  907. * @param bool $not
  908. * @return $this
  909. */
  910. public function whereBetween($column, array $values, $boolean = 'and', $not = false)
  911. {
  912. $type = 'between';
  913. $this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not');
  914. $this->addBinding($this->cleanBindings($values), 'where');
  915. return $this;
  916. }
  917. /**
  918. * Add an or where between statement to the query.
  919. *
  920. * @param string $column
  921. * @param array $values
  922. * @return \Illuminate\Database\Query\Builder|static
  923. */
  924. public function orWhereBetween($column, array $values)
  925. {
  926. return $this->whereBetween($column, $values, 'or');
  927. }
  928. /**
  929. * Add a where not between statement to the query.
  930. *
  931. * @param string $column
  932. * @param array $values
  933. * @param string $boolean
  934. * @return \Illuminate\Database\Query\Builder|static
  935. */
  936. public function whereNotBetween($column, array $values, $boolean = 'and')
  937. {
  938. return $this->whereBetween($column, $values, $boolean, true);
  939. }
  940. /**
  941. * Add an or where not between statement to the query.
  942. *
  943. * @param string $column
  944. * @param array $values
  945. * @return \Illuminate\Database\Query\Builder|static
  946. */
  947. public function orWhereNotBetween($column, array $values)
  948. {
  949. return $this->whereNotBetween($column, $values, 'or');
  950. }
  951. /**
  952. * Add an "or where not null" clause to the query.
  953. *
  954. * @param string $column
  955. * @return \Illuminate\Database\Query\Builder|static
  956. */
  957. public function orWhereNotNull($column)
  958. {
  959. return $this->whereNotNull($column, 'or');
  960. }
  961. /**
  962. * Add a "where date" statement to the query.
  963. *
  964. * @param string $column
  965. * @param string $operator
  966. * @param \DateTimeInterface|string $value
  967. * @param string $boolean
  968. * @return \Illuminate\Database\Query\Builder|static
  969. */
  970. public function whereDate($column, $operator, $value = null, $boolean = 'and')
  971. {
  972. [$value, $operator] = $this->prepareValueAndOperator(
  973. $value, $operator, func_num_args() === 2
  974. );
  975. if ($value instanceof DateTimeInterface) {
  976. $value = $value->format('Y-m-d');
  977. }
  978. return $this->addDateBasedWhere('Date', $column, $operator, $value, $boolean);
  979. }
  980. /**
  981. * Add an "or where date" statement to the query.
  982. *
  983. * @param string $column
  984. * @param string $operator
  985. * @param \DateTimeInterface|string $value
  986. * @return \Illuminate\Database\Query\Builder|static
  987. */
  988. public function orWhereDate($column, $operator, $value = null)
  989. {
  990. [$value, $operator] = $this->prepareValueAndOperator(
  991. $value, $operator, func_num_args() === 2
  992. );
  993. return $this->whereDate($column, $operator, $value, 'or');
  994. }
  995. /**
  996. * Add a "where time" statement to the query.
  997. *
  998. * @param string $column
  999. * @param string $operator
  1000. * @param \DateTimeInterface|string $value
  1001. * @param string $boolean
  1002. * @return \Illuminate\Database\Query\Builder|static
  1003. */
  1004. public function whereTime($column, $operator, $value = null, $boolean = 'and')
  1005. {
  1006. [$value, $operator] = $this->prepareValueAndOperator(
  1007. $value, $operator, func_num_args() === 2
  1008. );
  1009. if ($value instanceof DateTimeInterface) {
  1010. $value = $value->format('H:i:s');
  1011. }
  1012. return $this->addDateBasedWhere('Time', $column, $operator, $value, $boolean);
  1013. }
  1014. /**
  1015. * Add an "or where time" statement to the query.
  1016. *
  1017. * @param string $column
  1018. * @param string $operator
  1019. * @param \DateTimeInterface|string $value
  1020. * @return \Illuminate\Database\Query\Builder|static
  1021. */
  1022. public function orWhereTime($column, $operator, $value = null)
  1023. {
  1024. [$value, $operator] = $this->prepareValueAndOperator(
  1025. $value, $operator, func_num_args() === 2
  1026. );
  1027. return $this->whereTime($column, $operator, $value, 'or');
  1028. }
  1029. /**
  1030. * Add a "where day" statement to the query.
  1031. *
  1032. * @param string $column
  1033. * @param string $operator
  1034. * @param \DateTimeInterface|string $value
  1035. * @param string $boolean
  1036. * @return \Illuminate\Database\Query\Builder|static
  1037. */
  1038. public function whereDay($column, $operator, $value = null, $boolean = 'and')
  1039. {
  1040. [$value, $operator] = $this->prepareValueAndOperator(
  1041. $value, $operator, func_num_args() === 2
  1042. );
  1043. if ($value instanceof DateTimeInterface) {
  1044. $value = $value->format('d');
  1045. }
  1046. return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean);
  1047. }
  1048. /**
  1049. * Add an "or where day" statement to the query.
  1050. *
  1051. * @param string $column
  1052. * @param string $operator
  1053. * @param \DateTimeInterface|string $value
  1054. * @return \Illuminate\Database\Query\Builder|static
  1055. */
  1056. public function orWhereDay($column, $operator, $value = null)
  1057. {
  1058. [$value, $operator] = $this->prepareValueAndOperator(
  1059. $value, $operator, func_num_args() === 2
  1060. );
  1061. return $this->addDateBasedWhere('Day', $column, $operator, $value, 'or');
  1062. }
  1063. /**
  1064. * Add a "where month" statement to the query.
  1065. *
  1066. * @param string $column
  1067. * @param string $operator
  1068. * @param \DateTimeInterface|string $value
  1069. * @param string $boolean
  1070. * @return \Illuminate\Database\Query\Builder|static
  1071. */
  1072. public function whereMonth($column, $operator, $value = null, $boolean = 'and')
  1073. {
  1074. [$value, $operator] = $this->prepareValueAndOperator(
  1075. $value, $operator, func_num_args() === 2
  1076. );
  1077. if ($value instanceof DateTimeInterface) {
  1078. $value = $value->format('m');
  1079. }
  1080. return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean);
  1081. }
  1082. /**
  1083. * Add an "or where month" statement to the query.
  1084. *
  1085. * @param string $column
  1086. * @param string $operator
  1087. * @param \DateTimeInterface|string $value
  1088. * @return \Illuminate\Database\Query\Builder|static
  1089. */
  1090. public function orWhereMonth($column, $operator, $value = null)
  1091. {
  1092. [$value, $operator] = $this->prepareValueAndOperator(
  1093. $value, $operator, func_num_args() === 2
  1094. );
  1095. return $this->addDateBasedWhere('Month', $column, $operator, $value, 'or');
  1096. }
  1097. /**
  1098. * Add a "where year" statement to the query.
  1099. *
  1100. * @param string $column
  1101. * @param string $operator
  1102. * @param \DateTimeInterface|string|int $value
  1103. * @param string $boolean
  1104. * @return \Illuminate\Database\Query\Builder|static
  1105. */
  1106. public function whereYear($column, $operator, $value = null, $boolean = 'and')
  1107. {
  1108. [$value, $operator] = $this->prepareValueAndOperator(
  1109. $value, $operator, func_num_args() === 2
  1110. );
  1111. if ($value instanceof DateTimeInterface) {
  1112. $value = $value->format('Y');
  1113. }
  1114. return $this->addDateBasedWhere('Year', $column, $operator, $value, $boolean);
  1115. }
  1116. /**
  1117. * Add an "or where year" statement to the query.
  1118. *
  1119. * @param string $column
  1120. * @param string $operator
  1121. * @param \DateTimeInterface|string|int $value
  1122. * @return \Illuminate\Database\Query\Builder|static
  1123. */
  1124. public function orWhereYear($column, $operator, $value = null)
  1125. {
  1126. [$value, $operator] = $this->prepareValueAndOperator(
  1127. $value, $operator, func_num_args() === 2
  1128. );
  1129. return $this->addDateBasedWhere('Year', $column, $operator, $value, 'or');
  1130. }
  1131. /**
  1132. * Add a date based (year, month, day, time) statement to the query.
  1133. *
  1134. * @param string $type
  1135. * @param string $column
  1136. * @param string $operator
  1137. * @param mixed $value
  1138. * @param string $boolean
  1139. * @return $this
  1140. */
  1141. protected function addDateBasedWhere($type, $column, $operator, $value, $boolean = 'and')
  1142. {
  1143. $this->wheres[] = compact('column', 'type', 'boolean', 'operator', 'value');
  1144. if (! $value instanceof Expression) {
  1145. $this->addBinding($value, 'where');
  1146. }
  1147. return $this;
  1148. }
  1149. /**
  1150. * Add a nested where statement to the query.
  1151. *
  1152. * @param \Closure $callback
  1153. * @param string $boolean
  1154. * @return \Illuminate\Database\Query\Builder|static
  1155. */
  1156. public function whereNested(Closure $callback, $boolean = 'and')
  1157. {
  1158. call_user_func($callback, $query = $this->forNestedWhere());
  1159. return $this->addNestedWhereQuery($query, $boolean);
  1160. }
  1161. /**
  1162. * Create a new query instance for nested where condition.
  1163. *
  1164. * @return \Illuminate\Database\Query\Builder
  1165. */
  1166. public function forNestedWhere()
  1167. {
  1168. return $this->newQuery()->from($this->from);
  1169. }
  1170. /**
  1171. * Add another query builder as a nested where to the query builder.
  1172. *
  1173. * @param \Illuminate\Database\Query\Builder|static $query
  1174. * @param string $boolean
  1175. * @return $this
  1176. */
  1177. public function addNestedWhereQuery($query, $boolean = 'and')
  1178. {
  1179. if (count($query->wheres)) {
  1180. $type = 'Nested';
  1181. $this->wheres[] = compact('type', 'query', 'boolean');
  1182. $this->addBinding($query->getRawBindings()['where'], 'where');
  1183. }
  1184. return $this;
  1185. }
  1186. /**
  1187. * Add a full sub-select to the query.
  1188. *
  1189. * @param string $column
  1190. * @param string $operator
  1191. * @param \Closure $callback
  1192. * @param string $boolean
  1193. * @return $this
  1194. */
  1195. protected function whereSub($column, $operator, Closure $callback, $boolean)
  1196. {
  1197. $type = 'Sub';
  1198. // Once we have the query instance we can simply execute it so it can add all
  1199. // of the sub-select's conditions to itself, and then we can cache it off
  1200. // in the array of where clauses for the "main" parent query instance.
  1201. call_user_func($callback, $query = $this->forSubQuery());
  1202. $this->wheres[] = compact(
  1203. 'type', 'column', 'operator', 'query', 'boolean'
  1204. );
  1205. $this->addBinding($query->getBindings(), 'where');
  1206. return $this;
  1207. }
  1208. /**
  1209. * Add an exists clause to the query.
  1210. *
  1211. * @param \Closure $callback
  1212. * @param string $boolean
  1213. * @param bool $not
  1214. * @return $this
  1215. */
  1216. public function whereExists(Closure $callback, $boolean = 'and', $not = false)
  1217. {
  1218. $query = $this->forSubQuery();
  1219. // Similar to the sub-select clause, we will create a new query instance so
  1220. // the developer may cleanly specify the entire exists query and we will
  1221. // compile the whole thing in the grammar and insert it into the SQL.
  1222. call_user_func($callback, $query);
  1223. return $this->addWhereExistsQuery($query, $boolean, $not);
  1224. }
  1225. /**
  1226. * Add an or exists clause to the query.
  1227. *
  1228. * @param \Closure $callback
  1229. * @param bool $not
  1230. * @return \Illuminate\Database\Query\Builder|static
  1231. */
  1232. public function orWhereExists(Closure $callback, $not = false)
  1233. {
  1234. return $this->whereExists($callback, 'or', $not);
  1235. }
  1236. /**
  1237. * Add a where not exists clause to the query.
  1238. *
  1239. * @param \Closure $callback
  1240. * @param string $boolean
  1241. * @return \Illuminate\Database\Query\Builder|static
  1242. */
  1243. public function whereNotExists(Closure $callback, $boolean = 'and')
  1244. {
  1245. return $this->whereExists($callback, $boolean, true);
  1246. }
  1247. /**
  1248. * Add a where not exists clause to the query.
  1249. *
  1250. * @param \Closure $callback
  1251. * @return \Illuminate\Database\Query\Builder|static
  1252. */
  1253. public function orWhereNotExists(Closure $callback)
  1254. {
  1255. return $this->orWhereExists($callback, true);
  1256. }
  1257. /**
  1258. * Add an exists clause to the query.
  1259. *
  1260. * @param \Illuminate\Database\Query\Builder $query
  1261. * @param string $boolean
  1262. * @param bool $not
  1263. * @return $this
  1264. */
  1265. public function addWhereExistsQuery(self $query, $boolean = 'and', $not = false)
  1266. {
  1267. $type = $not ? 'NotExists' : 'Exists';
  1268. $this->wheres[] = compact('type', 'query', 'boolean');
  1269. $this->addBinding($query->getBindings(), 'where');
  1270. return $this;
  1271. }
  1272. /**
  1273. * Adds a where condition using row values.
  1274. *
  1275. * @param array $columns
  1276. * @param string $operator
  1277. * @param array $values
  1278. * @param string $boolean
  1279. * @return $this
  1280. */
  1281. public function whereRowValues($columns, $operator, $values, $boolean = 'and')
  1282. {
  1283. if (count($columns) !== count($values)) {
  1284. throw new InvalidArgumentException('The number of columns must match the number of values');
  1285. }
  1286. $type = 'RowValues';
  1287. $this->wheres[] = compact('type', 'columns', 'operator', 'values', 'boolean');
  1288. $this->addBinding($this->cleanBindings($values));
  1289. return $this;
  1290. }
  1291. /**
  1292. * Adds a or where condition using row values.
  1293. *
  1294. * @param array $columns
  1295. * @param string $operator
  1296. * @param array $values
  1297. * @return $this
  1298. */
  1299. public function orWhereRowValues($columns, $operator, $values)
  1300. {
  1301. return $this->whereRowValues($columns, $operator, $values, 'or');
  1302. }
  1303. /**
  1304. * Add a "where JSON contains" clause to the query.
  1305. *
  1306. * @param string $column
  1307. * @param mixed $value
  1308. * @param string $boolean
  1309. * @param bool $not
  1310. * @return $this
  1311. */
  1312. public function whereJsonContains($column, $value, $boolean = 'and', $not = false)
  1313. {
  1314. $type = 'JsonContains';
  1315. $this->wheres[] = compact('type', 'column', 'value', 'boolean', 'not');
  1316. if (! $value instanceof Expression) {
  1317. $this->addBinding($this->grammar->prepareBindingForJsonContains($value));
  1318. }
  1319. return $this;
  1320. }
  1321. /**
  1322. * Add a "or where JSON contains" clause to the query.
  1323. *
  1324. * @param string $column
  1325. * @param mixed $value
  1326. * @return $this
  1327. */
  1328. public function orWhereJsonContains($column, $value)
  1329. {
  1330. return $this->whereJsonContains($column, $value, 'or');
  1331. }
  1332. /**
  1333. * Add a "where JSON not contains" clause to the query.
  1334. *
  1335. * @param string $column
  1336. * @param mixed $value
  1337. * @param string $boolean
  1338. * @return $this
  1339. */
  1340. public function whereJsonDoesntContain($column, $value, $boolean = 'and')
  1341. {
  1342. return $this->whereJsonContains($column, $value, $boolean, true);
  1343. }
  1344. /**
  1345. * Add a "or where JSON not contains" clause to the query.
  1346. *
  1347. * @param string $column
  1348. * @param mixed $value
  1349. * @return $this
  1350. */
  1351. public function orWhereJsonDoesntContain($column, $value)
  1352. {
  1353. return $this->whereJsonDoesntContain($column, $value, 'or');
  1354. }
  1355. /**
  1356. * Add a "where JSON length" clause to the query.
  1357. *
  1358. * @param string $column
  1359. * @param mixed $operator
  1360. * @param mixed $value
  1361. * @param string $boolean
  1362. * @return $this
  1363. */
  1364. public function whereJsonLength($column, $operator, $value = null, $boolean = 'and')
  1365. {
  1366. $type = 'JsonLength';
  1367. [$value, $operator] = $this->prepareValueAndOperator(
  1368. $value, $operator, func_num_args() === 2
  1369. );
  1370. $this->wheres[] = compact('type', 'column', 'operator', 'value', 'boolean');
  1371. if (! $value instanceof Expression) {
  1372. $this->addBinding($value);
  1373. }
  1374. return $this;
  1375. }
  1376. /**
  1377. * Add a "or where JSON length" clause to the query.
  1378. *
  1379. * @param string $column
  1380. * @param mixed $operator
  1381. * @param mixed $value
  1382. * @return $this
  1383. */
  1384. public function orWhereJsonLength($column, $operator, $value = null)
  1385. {
  1386. [$value, $operator] = $this->prepareValueAndOperator(
  1387. $value, $operator, func_num_args() === 2
  1388. );
  1389. return $this->whereJsonLength($column, $operator, $value, 'or');
  1390. }
  1391. /**
  1392. * Handles dynamic "where" clauses to the query.
  1393. *
  1394. * @param string $method
  1395. * @param string $parameters
  1396. * @return $this
  1397. */
  1398. public function dynamicWhere($method, $parameters)
  1399. {
  1400. $finder = substr($method, 5);
  1401. $segments = preg_split(
  1402. '/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE
  1403. );
  1404. // The connector variable will determine which connector will be used for the
  1405. // query condition. We will change it as we come across new boolean values
  1406. // in the dynamic method strings, which could contain a number of these.
  1407. $connector = 'and';
  1408. $index = 0;
  1409. foreach ($segments as $segment) {
  1410. // If the segment is not a boolean connector, we can assume it is a column's name
  1411. // and we will add it to the query as a new constraint as a where clause, then
  1412. // we can keep iterating through the dynamic method string's segments again.
  1413. if ($segment !== 'And' && $segment !== 'Or') {
  1414. $this->addDynamic($segment, $connector, $parameters, $index);
  1415. $index++;
  1416. }
  1417. // Otherwise, we will store the connector so we know how the next where clause we
  1418. // find in the query should be connected to the previous ones, meaning we will
  1419. // have the proper boolean connector to connect the next where clause found.
  1420. else {
  1421. $connector = $segment;
  1422. }
  1423. }
  1424. return $this;
  1425. }
  1426. /**
  1427. * Add a single dynamic where clause statement to the query.
  1428. *
  1429. * @param string $segment
  1430. * @param string $connector
  1431. * @param array $parameters
  1432. * @param int $index
  1433. * @return void
  1434. */
  1435. protected function addDynamic($segment, $connector, $parameters, $index)
  1436. {
  1437. // Once we have parsed out the columns and formatted the boolean operators we
  1438. // are ready to add it to this query as a where clause just like any other
  1439. // clause on the query. Then we'll increment the parameter index values.
  1440. $bool = strtolower($connector);
  1441. $this->where(Str::snake($segment), '=', $parameters[$index], $bool);
  1442. }
  1443. /**
  1444. * Add a "group by" clause to the query.
  1445. *
  1446. * @param array ...$groups
  1447. * @return $this
  1448. */
  1449. public function groupBy(...$groups)
  1450. {
  1451. foreach ($groups as $group) {
  1452. $this->groups = array_merge(
  1453. (array) $this->groups,
  1454. Arr::wrap($group)
  1455. );
  1456. }
  1457. return $this;
  1458. }
  1459. /**
  1460. * Add a "having" clause to the query.
  1461. *
  1462. * @param string $column
  1463. * @param string|null $operator
  1464. * @param string|null $value
  1465. * @param string $boolean
  1466. * @return $this
  1467. */
  1468. public function having($column, $operator = null, $value = null, $boolean = 'and')
  1469. {
  1470. $type = 'Basic';
  1471. // Here we will make some assumptions about the operator. If only 2 values are
  1472. // passed to the method, we will assume that the operator is an equals sign
  1473. // and keep going. Otherwise, we'll require the operator to be passed in.
  1474. [$value, $operator] = $this->prepareValueAndOperator(
  1475. $value, $operator, func_num_args() === 2
  1476. );
  1477. // If the given operator is not found in the list of valid operators we will
  1478. // assume that the developer is just short-cutting the '=' operators and
  1479. // we will set the operators to '=' and set the values appropriately.
  1480. if ($this->invalidOperator($operator)) {
  1481. [$value, $operator] = [$operator, '='];
  1482. }
  1483. $this->havings[] = compact('type', 'column', 'operator', 'value', 'boolean');
  1484. if (! $value instanceof Expression) {
  1485. $this->addBinding($value, 'having');
  1486. }
  1487. return $this;
  1488. }
  1489. /**
  1490. * Add a "or having" clause to the query.
  1491. *
  1492. * @param string $column
  1493. * @param string|null $operator
  1494. * @param string|null $value
  1495. * @return \Illuminate\Database\Query\Builder|static
  1496. */
  1497. public function orHaving($column, $operator = null, $value = null)
  1498. {
  1499. [$value, $operator] = $this->prepareValueAndOperator(
  1500. $value, $operator, func_num_args() === 2
  1501. );
  1502. return $this->having($column, $operator, $value, 'or');
  1503. }
  1504. /**
  1505. * Add a "having between " clause to the query.
  1506. *
  1507. * @param string $column
  1508. * @param array $values
  1509. * @param string $boolean
  1510. * @param bool $not
  1511. * @return \Illuminate\Database\Query\Builder|static
  1512. */
  1513. public function havingBetween($column, array $values, $boolean = 'and', $not = false)
  1514. {
  1515. $type = 'between';
  1516. $this->havings[] = compact('type', 'column', 'values', 'boolean', 'not');
  1517. $this->addBinding($this->cleanBindings($values), 'having');
  1518. return $this;
  1519. }
  1520. /**
  1521. * Add a raw having clause to the query.
  1522. *
  1523. * @param string $sql
  1524. * @param array $bindings
  1525. * @param string $boolean
  1526. * @return $this
  1527. */
  1528. public function havingRaw($sql, array $bindings = [], $boolean = 'and')
  1529. {
  1530. $type = 'Raw';
  1531. $this->havings[] = compact('type', 'sql', 'boolean');
  1532. $this->addBinding($bindings, 'having');
  1533. return $this;
  1534. }
  1535. /**
  1536. * Add a raw or having clause to the query.
  1537. *
  1538. * @param string $sql
  1539. * @param array $bindings
  1540. * @return \Illuminate\Database\Query\Builder|static
  1541. */
  1542. public function orHavingRaw($sql, array $bindings = [])
  1543. {
  1544. return $this->havingRaw($sql, $bindings, 'or');
  1545. }
  1546. /**
  1547. * Add an "order by" clause to the query.
  1548. *
  1549. * @param string $column
  1550. * @param string $direction
  1551. * @return $this
  1552. *
  1553. * @throws \InvalidArgumentException
  1554. */
  1555. public function orderBy($column, $direction = 'asc')
  1556. {
  1557. $direction = strtolower($direction);
  1558. if (! in_array($direction, ['asc', 'desc'], true)) {
  1559. throw new InvalidArgumentException('Order direction must be "asc" or "desc".');
  1560. }
  1561. $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [
  1562. 'column' => $column,
  1563. 'direction' => $direction,
  1564. ];
  1565. return $this;
  1566. }
  1567. /**
  1568. * Add a descending "order by" clause to the query.
  1569. *
  1570. * @param string $column
  1571. * @return $this
  1572. */
  1573. public function orderByDesc($column)
  1574. {
  1575. return $this->orderBy($column, 'desc');
  1576. }
  1577. /**
  1578. * Add an "order by" clause for a timestamp to the query.
  1579. *
  1580. * @param string $column
  1581. * @return \Illuminate\Database\Query\Builder|static
  1582. */
  1583. public function latest($column = 'created_at')
  1584. {
  1585. return $this->orderBy($column, 'desc');
  1586. }
  1587. /**
  1588. * Add an "order by" clause for a timestamp to the query.
  1589. *
  1590. * @param string $column
  1591. * @return \Illuminate\Database\Query\Builder|static
  1592. */
  1593. public function oldest($column = 'created_at')
  1594. {
  1595. return $this->orderBy($column, 'asc');
  1596. }
  1597. /**
  1598. * Put the query's results in random order.
  1599. *
  1600. * @param string $seed
  1601. * @return $this
  1602. */
  1603. public function inRandomOrder($seed = '')
  1604. {
  1605. return $this->orderByRaw($this->grammar->compileRandom($seed));
  1606. }
  1607. /**
  1608. * Add a raw "order by" clause to the query.
  1609. *
  1610. * @param string $sql
  1611. * @param array $bindings
  1612. * @return $this
  1613. */
  1614. public function orderByRaw($sql, $bindings = [])
  1615. {
  1616. $type = 'Raw';
  1617. $this->{$this->unions ? 'unionOrders' : 'orders'}[] = compact('type', 'sql');
  1618. $this->addBinding($bindings, 'order');
  1619. return $this;
  1620. }
  1621. /**
  1622. * Alias to set the "offset" value of the query.
  1623. *
  1624. * @param int $value
  1625. * @return \Illuminate\Database\Query\Builder|static
  1626. */
  1627. public function skip($value)
  1628. {
  1629. return $this->offset($value);
  1630. }
  1631. /**
  1632. * Set the "offset" value of the query.
  1633. *
  1634. * @param int $value
  1635. * @return $this
  1636. */
  1637. public function offset($value)
  1638. {
  1639. $property = $this->unions ? 'unionOffset' : 'offset';
  1640. $this->$property = max(0, $value);
  1641. return $this;
  1642. }
  1643. /**
  1644. * Alias to set the "limit" value of the query.
  1645. *
  1646. * @param int $value
  1647. * @return \Illuminate\Database\Query\Builder|static
  1648. */
  1649. public function take($value)
  1650. {
  1651. return $this->limit($value);
  1652. }
  1653. /**
  1654. * Set the "limit" value of the query.
  1655. *
  1656. * @param int $value
  1657. * @return $this
  1658. */
  1659. public function limit($value)
  1660. {
  1661. $property = $this->unions ? 'unionLimit' : 'limit';
  1662. if ($value >= 0) {
  1663. $this->$property = $value;
  1664. }
  1665. return $this;
  1666. }
  1667. /**
  1668. * Set the limit and offset for a given page.
  1669. *
  1670. * @param int $page
  1671. * @param int $perPage
  1672. * @return \Illuminate\Database\Query\Builder|static
  1673. */
  1674. public function forPage($page, $perPage = 15)
  1675. {
  1676. return $this->skip(($page - 1) * $perPage)->take($perPage);
  1677. }
  1678. /**
  1679. * Constrain the query to the previous "page" of results before a given ID.
  1680. *
  1681. * @param int $perPage
  1682. * @param int|null $lastId
  1683. * @param string $column
  1684. * @return \Illuminate\Database\Query\Builder|static
  1685. */
  1686. public function forPageBeforeId($perPage = 15, $lastId = 0, $column = 'id')
  1687. {
  1688. $this->orders = $this->removeExistingOrdersFor($column);
  1689. if (! is_null($lastId)) {
  1690. $this->where($column, '<', $lastId);
  1691. }
  1692. return $this->orderBy($column, 'desc')
  1693. ->take($perPage);
  1694. }
  1695. /**
  1696. * Constrain the query to the next "page" of results after a given ID.
  1697. *
  1698. * @param int $perPage
  1699. * @param int|null $lastId
  1700. * @param string $column
  1701. * @return \Illuminate\Database\Query\Builder|static
  1702. */
  1703. public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id')
  1704. {
  1705. $this->orders = $this->removeExistingOrdersFor($column);
  1706. if (! is_null($lastId)) {
  1707. $this->where($column, '>', $lastId);
  1708. }
  1709. return $this->orderBy($column, 'asc')
  1710. ->take($perPage);
  1711. }
  1712. /**
  1713. * Get an array with all orders with a given column removed.
  1714. *
  1715. * @param string $column
  1716. * @return array
  1717. */
  1718. protected function removeExistingOrdersFor($column)
  1719. {
  1720. return Collection::make($this->orders)
  1721. ->reject(function ($order) use ($column) {
  1722. return isset($order['column'])
  1723. ? $order['column'] === $column : false;
  1724. })->values()->all();
  1725. }
  1726. /**
  1727. * Add a union statement to the query.
  1728. *
  1729. * @param \Illuminate\Database\Query\Builder|\Closure $query
  1730. * @param bool $all
  1731. * @return \Illuminate\Database\Query\Builder|static
  1732. */
  1733. public function union($query, $all = false)
  1734. {
  1735. if ($query instanceof Closure) {
  1736. call_user_func($query, $query = $this->newQuery());
  1737. }
  1738. $this->unions[] = compact('query', 'all');
  1739. $this->addBinding($query->getBindings(), 'union');
  1740. return $this;
  1741. }
  1742. /**
  1743. * Add a union all statement to the query.
  1744. *
  1745. * @param \Illuminate\Database\Query\Builder|\Closure $query
  1746. * @return \Illuminate\Database\Query\Builder|static
  1747. */
  1748. public function unionAll($query)
  1749. {
  1750. return $this->union($query, true);
  1751. }
  1752. /**
  1753. * Lock the selected rows in the table.
  1754. *
  1755. * @param string|bool $value
  1756. * @return $this
  1757. */
  1758. public function lock($value = true)
  1759. {
  1760. $this->lock = $value;
  1761. if (! is_null($this->lock)) {
  1762. $this->useWritePdo();
  1763. }
  1764. return $this;
  1765. }
  1766. /**
  1767. * Lock the selected rows in the table for updating.
  1768. *
  1769. * @return \Illuminate\Database\Query\Builder
  1770. */
  1771. public function lockForUpdate()
  1772. {
  1773. return $this->lock(true);
  1774. }
  1775. /**
  1776. * Share lock the selected rows in the table.
  1777. *
  1778. * @return \Illuminate\Database\Query\Builder
  1779. */
  1780. public function sharedLock()
  1781. {
  1782. return $this->lock(false);
  1783. }
  1784. /**
  1785. * Get the SQL representation of the query.
  1786. *
  1787. * @return string
  1788. */
  1789. public function toSql()
  1790. {
  1791. return $this->grammar->compileSelect($this);
  1792. }
  1793. /**
  1794. * Execute a query for a single record by ID.
  1795. *
  1796. * @param int $id
  1797. * @param array $columns
  1798. * @return mixed|static
  1799. */
  1800. public function find($id, $columns = ['*'])
  1801. {
  1802. return $this->where('id', '=', $id)->first($columns);
  1803. }
  1804. /**
  1805. * Get a single column's value from the first result of a query.
  1806. *
  1807. * @param string $column
  1808. * @return mixed
  1809. */
  1810. public function value($column)
  1811. {
  1812. $result = (array) $this->first([$column]);
  1813. return count($result) > 0 ? reset($result) : null;
  1814. }
  1815. /**
  1816. * Execute the query as a "select" statement.
  1817. *
  1818. * @param array|string $columns
  1819. * @return \Illuminate\Support\Collection
  1820. */
  1821. public function get($columns = ['*'])
  1822. {
  1823. return collect($this->onceWithColumns(Arr::wrap($columns), function () {
  1824. return $this->processor->processSelect($this, $this->runSelect());
  1825. }));
  1826. }
  1827. /**
  1828. * Run the query as a "select" statement against the connection.
  1829. *
  1830. * @return array
  1831. */
  1832. protected function runSelect()
  1833. {
  1834. return $this->connection->select(
  1835. $this->toSql(), $this->getBindings(), ! $this->useWritePdo
  1836. );
  1837. }
  1838. /**
  1839. * Paginate the given query into a simple paginator.
  1840. *
  1841. * @param int $perPage
  1842. * @param array $columns
  1843. * @param string $pageName
  1844. * @param int|null $page
  1845. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1846. */
  1847. public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null)
  1848. {
  1849. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  1850. $total = $this->getCountForPagination($columns);
  1851. $results = $total ? $this->forPage($page, $perPage)->get($columns) : collect();
  1852. return $this->paginator($results, $total, $perPage, $page, [
  1853. 'path' => Paginator::resolveCurrentPath(),
  1854. 'pageName' => $pageName,
  1855. ]);
  1856. }
  1857. /**
  1858. * Get a paginator only supporting simple next and previous links.
  1859. *
  1860. * This is more efficient on larger data-sets, etc.
  1861. *
  1862. * @param int $perPage
  1863. * @param array $columns
  1864. * @param string $pageName
  1865. * @param int|null $page
  1866. * @return \Illuminate\Contracts\Pagination\Paginator
  1867. */
  1868. public function simplePaginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null)
  1869. {
  1870. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  1871. $this->skip(($page - 1) * $perPage)->take($perPage + 1);
  1872. return $this->simplePaginator($this->get($columns), $perPage, $page, [
  1873. 'path' => Paginator::resolveCurrentPath(),
  1874. 'pageName' => $pageName,
  1875. ]);
  1876. }
  1877. /**
  1878. * Get the count of the total records for the paginator.
  1879. *
  1880. * @param array $columns
  1881. * @return int
  1882. */
  1883. public function getCountForPagination($columns = ['*'])
  1884. {
  1885. $results = $this->runPaginationCountQuery($columns);
  1886. // Once we have run the pagination count query, we will get the resulting count and
  1887. // take into account what type of query it was. When there is a group by we will
  1888. // just return the count of the entire results set since that will be correct.
  1889. if (isset($this->groups)) {
  1890. return count($results);
  1891. } elseif (! isset($results[0])) {
  1892. return 0;
  1893. } elseif (is_object($results[0])) {
  1894. return (int) $results[0]->aggregate;
  1895. }
  1896. return (int) array_change_key_case((array) $results[0])['aggregate'];
  1897. }
  1898. /**
  1899. * Run a pagination count query.
  1900. *
  1901. * @param array $columns
  1902. * @return array
  1903. */
  1904. protected function runPaginationCountQuery($columns = ['*'])
  1905. {
  1906. $without = $this->unions ? ['orders', 'limit', 'offset'] : ['columns', 'orders', 'limit', 'offset'];
  1907. return $this->cloneWithout($without)
  1908. ->cloneWithoutBindings($this->unions ? ['order'] : ['select', 'order'])
  1909. ->setAggregate('count', $this->withoutSelectAliases($columns))
  1910. ->get()->all();
  1911. }
  1912. /**
  1913. * Remove the column aliases since they will break count queries.
  1914. *
  1915. * @param array $columns
  1916. * @return array
  1917. */
  1918. protected function withoutSelectAliases(array $columns)
  1919. {
  1920. return array_map(function ($column) {
  1921. return is_string($column) && ($aliasPosition = stripos($column, ' as ')) !== false
  1922. ? substr($column, 0, $aliasPosition) : $column;
  1923. }, $columns);
  1924. }
  1925. /**
  1926. * Get a generator for the given query.
  1927. *
  1928. * @return \Generator
  1929. */
  1930. public function cursor()
  1931. {
  1932. if (is_null($this->columns)) {
  1933. $this->columns = ['*'];
  1934. }
  1935. return $this->connection->cursor(
  1936. $this->toSql(), $this->getBindings(), ! $this->useWritePdo
  1937. );
  1938. }
  1939. /**
  1940. * Chunk the results of a query by comparing numeric IDs.
  1941. *
  1942. * @param int $count
  1943. * @param callable $callback
  1944. * @param string $column
  1945. * @param string|null $alias
  1946. * @return bool
  1947. */
  1948. public function chunkById($count, callable $callback, $column = 'id', $alias = null)
  1949. {
  1950. $alias = $alias ?: $column;
  1951. $lastId = null;
  1952. do {
  1953. $clone = clone $this;
  1954. // We'll execute the query for the given page and get the results. If there are
  1955. // no results we can just break and return from here. When there are results
  1956. // we will call the callback with the current chunk of these results here.
  1957. $results = $clone->forPageAfterId($count, $lastId, $column)->get();
  1958. $countResults = $results->count();
  1959. if ($countResults == 0) {
  1960. break;
  1961. }
  1962. // On each chunk result set, we will pass them to the callback and then let the
  1963. // developer take care of everything within the callback, which allows us to
  1964. // keep the memory low for spinning through large result sets for working.
  1965. if ($callback($results) === false) {
  1966. return false;
  1967. }
  1968. $lastId = $results->last()->{$alias};
  1969. unset($results);
  1970. } while ($countResults == $count);
  1971. return true;
  1972. }
  1973. /**
  1974. * Throw an exception if the query doesn't have an orderBy clause.
  1975. *
  1976. * @return void
  1977. *
  1978. * @throws \RuntimeException
  1979. */
  1980. protected function enforceOrderBy()
  1981. {
  1982. if (empty($this->orders) && empty($this->unionOrders)) {
  1983. throw new RuntimeException('You must specify an orderBy clause when using this function.');
  1984. }
  1985. }
  1986. /**
  1987. * Get an array with the values of a given column.
  1988. *
  1989. * @param string $column
  1990. * @param string|null $key
  1991. * @return \Illuminate\Support\Collection
  1992. */
  1993. public function pluck($column, $key = null)
  1994. {
  1995. // First, we will need to select the results of the query accounting for the
  1996. // given columns / key. Once we have the results, we will be able to take
  1997. // the results and get the exact data that was requested for the query.
  1998. $queryResult = $this->onceWithColumns(
  1999. is_null($key) ? [$column] : [$column, $key],
  2000. function () {
  2001. return $this->processor->processSelect(
  2002. $this, $this->runSelect()
  2003. );
  2004. }
  2005. );
  2006. if (empty($queryResult)) {
  2007. return collect();
  2008. }
  2009. // If the columns are qualified with a table or have an alias, we cannot use
  2010. // those directly in the "pluck" operations since the results from the DB
  2011. // are only keyed by the column itself. We'll strip the table out here.
  2012. $column = $this->stripTableForPluck($column);
  2013. $key = $this->stripTableForPluck($key);
  2014. return is_array($queryResult[0])
  2015. ? $this->pluckFromArrayColumn($queryResult, $column, $key)
  2016. : $this->pluckFromObjectColumn($queryResult, $column, $key);
  2017. }
  2018. /**
  2019. * Strip off the table name or alias from a column identifier.
  2020. *
  2021. * @param string $column
  2022. * @return string|null
  2023. */
  2024. protected function stripTableForPluck($column)
  2025. {
  2026. return is_null($column) ? $column : last(preg_split('~\.| ~', $column));
  2027. }
  2028. /**
  2029. * Retrieve column values from rows represented as objects.
  2030. *
  2031. * @param array $queryResult
  2032. * @param string $column
  2033. * @param string $key
  2034. * @return \Illuminate\Support\Collection
  2035. */
  2036. protected function pluckFromObjectColumn($queryResult, $column, $key)
  2037. {
  2038. $results = [];
  2039. if (is_null($key)) {
  2040. foreach ($queryResult as $row) {
  2041. $results[] = $row->$column;
  2042. }
  2043. } else {
  2044. foreach ($queryResult as $row) {
  2045. $results[$row->$key] = $row->$column;
  2046. }
  2047. }
  2048. return collect($results);
  2049. }
  2050. /**
  2051. * Retrieve column values from rows represented as arrays.
  2052. *
  2053. * @param array $queryResult
  2054. * @param string $column
  2055. * @param string $key
  2056. * @return \Illuminate\Support\Collection
  2057. */
  2058. protected function pluckFromArrayColumn($queryResult, $column, $key)
  2059. {
  2060. $results = [];
  2061. if (is_null($key)) {
  2062. foreach ($queryResult as $row) {
  2063. $results[] = $row[$column];
  2064. }
  2065. } else {
  2066. foreach ($queryResult as $row) {
  2067. $results[$row[$key]] = $row[$column];
  2068. }
  2069. }
  2070. return collect($results);
  2071. }
  2072. /**
  2073. * Concatenate values of a given column as a string.
  2074. *
  2075. * @param string $column
  2076. * @param string $glue
  2077. * @return string
  2078. */
  2079. public function implode($column, $glue = '')
  2080. {
  2081. return $this->pluck($column)->implode($glue);
  2082. }
  2083. /**
  2084. * Determine if any rows exist for the current query.
  2085. *
  2086. * @return bool
  2087. */
  2088. public function exists()
  2089. {
  2090. $results = $this->connection->select(
  2091. $this->grammar->compileExists($this), $this->getBindings(), ! $this->useWritePdo
  2092. );
  2093. // If the results has rows, we will get the row and see if the exists column is a
  2094. // boolean true. If there is no results for this query we will return false as
  2095. // there are no rows for this query at all and we can return that info here.
  2096. if (isset($results[0])) {
  2097. $results = (array) $results[0];
  2098. return (bool) $results['exists'];
  2099. }
  2100. return false;
  2101. }
  2102. /**
  2103. * Determine if no rows exist for the current query.
  2104. *
  2105. * @return bool
  2106. */
  2107. public function doesntExist()
  2108. {
  2109. return ! $this->exists();
  2110. }
  2111. /**
  2112. * Retrieve the "count" result of the query.
  2113. *
  2114. * @param string $columns
  2115. * @return int
  2116. */
  2117. public function count($columns = '*')
  2118. {
  2119. return (int) $this->aggregate(__FUNCTION__, Arr::wrap($columns));
  2120. }
  2121. /**
  2122. * Retrieve the minimum value of a given column.
  2123. *
  2124. * @param string $column
  2125. * @return mixed
  2126. */
  2127. public function min($column)
  2128. {
  2129. return $this->aggregate(__FUNCTION__, [$column]);
  2130. }
  2131. /**
  2132. * Retrieve the maximum value of a given column.
  2133. *
  2134. * @param string $column
  2135. * @return mixed
  2136. */
  2137. public function max($column)
  2138. {
  2139. return $this->aggregate(__FUNCTION__, [$column]);
  2140. }
  2141. /**
  2142. * Retrieve the sum of the values of a given column.
  2143. *
  2144. * @param string $column
  2145. * @return mixed
  2146. */
  2147. public function sum($column)
  2148. {
  2149. $result = $this->aggregate(__FUNCTION__, [$column]);
  2150. return $result ?: 0;
  2151. }
  2152. /**
  2153. * Retrieve the average of the values of a given column.
  2154. *
  2155. * @param string $column
  2156. * @return mixed
  2157. */
  2158. public function avg($column)
  2159. {
  2160. return $this->aggregate(__FUNCTION__, [$column]);
  2161. }
  2162. /**
  2163. * Alias for the "avg" method.
  2164. *
  2165. * @param string $column
  2166. * @return mixed
  2167. */
  2168. public function average($column)
  2169. {
  2170. return $this->avg($column);
  2171. }
  2172. /**
  2173. * Execute an aggregate function on the database.
  2174. *
  2175. * @param string $function
  2176. * @param array $columns
  2177. * @return mixed
  2178. */
  2179. public function aggregate($function, $columns = ['*'])
  2180. {
  2181. $results = $this->cloneWithout($this->unions ? [] : ['columns'])
  2182. ->cloneWithoutBindings($this->unions ? [] : ['select'])
  2183. ->setAggregate($function, $columns)
  2184. ->get($columns);
  2185. if (! $results->isEmpty()) {
  2186. return array_change_key_case((array) $results[0])['aggregate'];
  2187. }
  2188. }
  2189. /**
  2190. * Execute a numeric aggregate function on the database.
  2191. *
  2192. * @param string $function
  2193. * @param array $columns
  2194. * @return float|int
  2195. */
  2196. public function numericAggregate($function, $columns = ['*'])
  2197. {
  2198. $result = $this->aggregate($function, $columns);
  2199. // If there is no result, we can obviously just return 0 here. Next, we will check
  2200. // if the result is an integer or float. If it is already one of these two data
  2201. // types we can just return the result as-is, otherwise we will convert this.
  2202. if (! $result) {
  2203. return 0;
  2204. }
  2205. if (is_int($result) || is_float($result)) {
  2206. return $result;
  2207. }
  2208. // If the result doesn't contain a decimal place, we will assume it is an int then
  2209. // cast it to one. When it does we will cast it to a float since it needs to be
  2210. // cast to the expected data type for the developers out of pure convenience.
  2211. return strpos((string) $result, '.') === false
  2212. ? (int) $result : (float) $result;
  2213. }
  2214. /**
  2215. * Set the aggregate property without running the query.
  2216. *
  2217. * @param string $function
  2218. * @param array $columns
  2219. * @return $this
  2220. */
  2221. protected function setAggregate($function, $columns)
  2222. {
  2223. $this->aggregate = compact('function', 'columns');
  2224. if (empty($this->groups)) {
  2225. $this->orders = null;
  2226. $this->bindings['order'] = [];
  2227. }
  2228. return $this;
  2229. }
  2230. /**
  2231. * Execute the given callback while selecting the given columns.
  2232. *
  2233. * After running the callback, the columns are reset to the original value.
  2234. *
  2235. * @param array $columns
  2236. * @param callable $callback
  2237. * @return mixed
  2238. */
  2239. protected function onceWithColumns($columns, $callback)
  2240. {
  2241. $original = $this->columns;
  2242. if (is_null($original)) {
  2243. $this->columns = $columns;
  2244. }
  2245. $result = $callback();
  2246. $this->columns = $original;
  2247. return $result;
  2248. }
  2249. /**
  2250. * Insert a new record into the database.
  2251. *
  2252. * @param array $values
  2253. * @return bool
  2254. */
  2255. public function insert(array $values)
  2256. {
  2257. // Since every insert gets treated like a batch insert, we will make sure the
  2258. // bindings are structured in a way that is convenient when building these
  2259. // inserts statements by verifying these elements are actually an array.
  2260. if (empty($values)) {
  2261. return true;
  2262. }
  2263. if (! is_array(reset($values))) {
  2264. $values = [$values];
  2265. }
  2266. // Here, we will sort the insert keys for every record so that each insert is
  2267. // in the same order for the record. We need to make sure this is the case
  2268. // so there are not any errors or problems when inserting these records.
  2269. else {
  2270. foreach ($values as $key => $value) {
  2271. ksort($value);
  2272. $values[$key] = $value;
  2273. }
  2274. }
  2275. // Finally, we will run this query against the database connection and return
  2276. // the results. We will need to also flatten these bindings before running
  2277. // the query so they are all in one huge, flattened array for execution.
  2278. return $this->connection->insert(
  2279. $this->grammar->compileInsert($this, $values),
  2280. $this->cleanBindings(Arr::flatten($values, 1))
  2281. );
  2282. }
  2283. /**
  2284. * Insert a new record and get the value of the primary key.
  2285. *
  2286. * @param array $values
  2287. * @param string|null $sequence
  2288. * @return int
  2289. */
  2290. public function insertGetId(array $values, $sequence = null)
  2291. {
  2292. $sql = $this->grammar->compileInsertGetId($this, $values, $sequence);
  2293. $values = $this->cleanBindings($values);
  2294. return $this->processor->processInsertGetId($this, $sql, $values, $sequence);
  2295. }
  2296. /**
  2297. * Insert new records into the table using a subquery.
  2298. *
  2299. * @param array $columns
  2300. * @param \Closure|\Illuminate\Database\Query\Builder|string $query
  2301. * @return bool
  2302. */
  2303. public function insertUsing(array $columns, $query)
  2304. {
  2305. [$sql, $bindings] = $this->createSub($query);
  2306. return $this->connection->insert(
  2307. $this->grammar->compileInsertUsing($this, $columns, $sql),
  2308. $this->cleanBindings($bindings)
  2309. );
  2310. }
  2311. /**
  2312. * Update a record in the database.
  2313. *
  2314. * @param array $values
  2315. * @return int
  2316. */
  2317. public function update(array $values)
  2318. {
  2319. $sql = $this->grammar->compileUpdate($this, $values);
  2320. return $this->connection->update($sql, $this->cleanBindings(
  2321. $this->grammar->prepareBindingsForUpdate($this->bindings, $values)
  2322. ));
  2323. }
  2324. /**
  2325. * Insert or update a record matching the attributes, and fill it with values.
  2326. *
  2327. * @param array $attributes
  2328. * @param array $values
  2329. * @return bool
  2330. */
  2331. public function updateOrInsert(array $attributes, array $values = [])
  2332. {
  2333. if (! $this->where($attributes)->exists()) {
  2334. return $this->insert(array_merge($attributes, $values));
  2335. }
  2336. if (empty($values)) {
  2337. return true;
  2338. }
  2339. return (bool) $this->take(1)->update($values);
  2340. }
  2341. /**
  2342. * Increment a column's value by a given amount.
  2343. *
  2344. * @param string $column
  2345. * @param float|int $amount
  2346. * @param array $extra
  2347. * @return int
  2348. */
  2349. public function increment($column, $amount = 1, array $extra = [])
  2350. {
  2351. if (! is_numeric($amount)) {
  2352. throw new InvalidArgumentException('Non-numeric value passed to increment method.');
  2353. }
  2354. $wrapped = $this->grammar->wrap($column);
  2355. $columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra);
  2356. return $this->update($columns);
  2357. }
  2358. /**
  2359. * Decrement a column's value by a given amount.
  2360. *
  2361. * @param string $column
  2362. * @param float|int $amount
  2363. * @param array $extra
  2364. * @return int
  2365. */
  2366. public function decrement($column, $amount = 1, array $extra = [])
  2367. {
  2368. if (! is_numeric($amount)) {
  2369. throw new InvalidArgumentException('Non-numeric value passed to decrement method.');
  2370. }
  2371. $wrapped = $this->grammar->wrap($column);
  2372. $columns = array_merge([$column => $this->raw("$wrapped - $amount")], $extra);
  2373. return $this->update($columns);
  2374. }
  2375. /**
  2376. * Delete a record from the database.
  2377. *
  2378. * @param mixed $id
  2379. * @return int
  2380. */
  2381. public function delete($id = null)
  2382. {
  2383. // If an ID is passed to the method, we will set the where clause to check the
  2384. // ID to let developers to simply and quickly remove a single row from this
  2385. // database without manually specifying the "where" clauses on the query.
  2386. if (! is_null($id)) {
  2387. $this->where($this->from.'.id', '=', $id);
  2388. }
  2389. return $this->connection->delete(
  2390. $this->grammar->compileDelete($this), $this->cleanBindings(
  2391. $this->grammar->prepareBindingsForDelete($this->bindings)
  2392. )
  2393. );
  2394. }
  2395. /**
  2396. * Run a truncate statement on the table.
  2397. *
  2398. * @return void
  2399. */
  2400. public function truncate()
  2401. {
  2402. foreach ($this->grammar->compileTruncate($this) as $sql => $bindings) {
  2403. $this->connection->statement($sql, $bindings);
  2404. }
  2405. }
  2406. /**
  2407. * Get a new instance of the query builder.
  2408. *
  2409. * @return \Illuminate\Database\Query\Builder
  2410. */
  2411. public function newQuery()
  2412. {
  2413. return new static($this->connection, $this->grammar, $this->processor);
  2414. }
  2415. /**
  2416. * Create a new query instance for a sub-query.
  2417. *
  2418. * @return \Illuminate\Database\Query\Builder
  2419. */
  2420. protected function forSubQuery()
  2421. {
  2422. return $this->newQuery();
  2423. }
  2424. /**
  2425. * Create a raw database expression.
  2426. *
  2427. * @param mixed $value
  2428. * @return \Illuminate\Database\Query\Expression
  2429. */
  2430. public function raw($value)
  2431. {
  2432. return $this->connection->raw($value);
  2433. }
  2434. /**
  2435. * Get the current query value bindings in a flattened array.
  2436. *
  2437. * @return array
  2438. */
  2439. public function getBindings()
  2440. {
  2441. return Arr::flatten($this->bindings);
  2442. }
  2443. /**
  2444. * Get the raw array of bindings.
  2445. *
  2446. * @return array
  2447. */
  2448. public function getRawBindings()
  2449. {
  2450. return $this->bindings;
  2451. }
  2452. /**
  2453. * Set the bindings on the query builder.
  2454. *
  2455. * @param array $bindings
  2456. * @param string $type
  2457. * @return $this
  2458. *
  2459. * @throws \InvalidArgumentException
  2460. */
  2461. public function setBindings(array $bindings, $type = 'where')
  2462. {
  2463. if (! array_key_exists($type, $this->bindings)) {
  2464. throw new InvalidArgumentException("Invalid binding type: {$type}.");
  2465. }
  2466. $this->bindings[$type] = $bindings;
  2467. return $this;
  2468. }
  2469. /**
  2470. * Add a binding to the query.
  2471. *
  2472. * @param mixed $value
  2473. * @param string $type
  2474. * @return $this
  2475. *
  2476. * @throws \InvalidArgumentException
  2477. */
  2478. public function addBinding($value, $type = 'where')
  2479. {
  2480. if (! array_key_exists($type, $this->bindings)) {
  2481. throw new InvalidArgumentException("Invalid binding type: {$type}.");
  2482. }
  2483. if (is_array($value)) {
  2484. $this->bindings[$type] = array_values(array_merge($this->bindings[$type], $value));
  2485. } else {
  2486. $this->bindings[$type][] = $value;
  2487. }
  2488. return $this;
  2489. }
  2490. /**
  2491. * Merge an array of bindings into our bindings.
  2492. *
  2493. * @param \Illuminate\Database\Query\Builder $query
  2494. * @return $this
  2495. */
  2496. public function mergeBindings(self $query)
  2497. {
  2498. $this->bindings = array_merge_recursive($this->bindings, $query->bindings);
  2499. return $this;
  2500. }
  2501. /**
  2502. * Remove all of the expressions from a list of bindings.
  2503. *
  2504. * @param array $bindings
  2505. * @return array
  2506. */
  2507. protected function cleanBindings(array $bindings)
  2508. {
  2509. return array_values(array_filter($bindings, function ($binding) {
  2510. return ! $binding instanceof Expression;
  2511. }));
  2512. }
  2513. /**
  2514. * Get the database connection instance.
  2515. *
  2516. * @return \Illuminate\Database\ConnectionInterface
  2517. */
  2518. public function getConnection()
  2519. {
  2520. return $this->connection;
  2521. }
  2522. /**
  2523. * Get the database query processor instance.
  2524. *
  2525. * @return \Illuminate\Database\Query\Processors\Processor
  2526. */
  2527. public function getProcessor()
  2528. {
  2529. return $this->processor;
  2530. }
  2531. /**
  2532. * Get the query grammar instance.
  2533. *
  2534. * @return \Illuminate\Database\Query\Grammars\Grammar
  2535. */
  2536. public function getGrammar()
  2537. {
  2538. return $this->grammar;
  2539. }
  2540. /**
  2541. * Use the write pdo for query.
  2542. *
  2543. * @return $this
  2544. */
  2545. public function useWritePdo()
  2546. {
  2547. $this->useWritePdo = true;
  2548. return $this;
  2549. }
  2550. /**
  2551. * Clone the query without the given properties.
  2552. *
  2553. * @param array $properties
  2554. * @return static
  2555. */
  2556. public function cloneWithout(array $properties)
  2557. {
  2558. return tap(clone $this, function ($clone) use ($properties) {
  2559. foreach ($properties as $property) {
  2560. $clone->{$property} = null;
  2561. }
  2562. });
  2563. }
  2564. /**
  2565. * Clone the query without the given bindings.
  2566. *
  2567. * @param array $except
  2568. * @return static
  2569. */
  2570. public function cloneWithoutBindings(array $except)
  2571. {
  2572. return tap(clone $this, function ($clone) use ($except) {
  2573. foreach ($except as $type) {
  2574. $clone->bindings[$type] = [];
  2575. }
  2576. });
  2577. }
  2578. /**
  2579. * Handle dynamic method calls into the method.
  2580. *
  2581. * @param string $method
  2582. * @param array $parameters
  2583. * @return mixed
  2584. *
  2585. * @throws \BadMethodCallException
  2586. */
  2587. public function __call($method, $parameters)
  2588. {
  2589. if (static::hasMacro($method)) {
  2590. return $this->macroCall($method, $parameters);
  2591. }
  2592. if (Str::startsWith($method, 'where')) {
  2593. return $this->dynamicWhere($method, $parameters);
  2594. }
  2595. static::throwBadMethodCallException($method);
  2596. }
  2597. }