Builder.php 78KB

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