Builder.php 92 KB

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