Builder.php 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297
  1. <?php
  2. namespace Illuminate\Database\Query;
  3. use BackedEnum;
  4. use Carbon\CarbonPeriod;
  5. use Closure;
  6. use DateTimeInterface;
  7. use Illuminate\Contracts\Database\Query\Builder as BuilderContract;
  8. use Illuminate\Contracts\Database\Query\ConditionExpression;
  9. use Illuminate\Contracts\Database\Query\Expression as ExpressionContract;
  10. use Illuminate\Contracts\Support\Arrayable;
  11. use Illuminate\Database\Concerns\BuildsQueries;
  12. use Illuminate\Database\Concerns\ExplainsQueries;
  13. use Illuminate\Database\ConnectionInterface;
  14. use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
  15. use Illuminate\Database\Eloquent\Relations\Relation;
  16. use Illuminate\Database\Query\Grammars\Grammar;
  17. use Illuminate\Database\Query\Processors\Processor;
  18. use Illuminate\Pagination\Paginator;
  19. use Illuminate\Support\Arr;
  20. use Illuminate\Support\Collection;
  21. use Illuminate\Support\LazyCollection;
  22. use Illuminate\Support\Str;
  23. use Illuminate\Support\Traits\ForwardsCalls;
  24. use Illuminate\Support\Traits\Macroable;
  25. use InvalidArgumentException;
  26. use LogicException;
  27. use RuntimeException;
  28. use UnitEnum;
  29. class Builder implements BuilderContract
  30. {
  31. use BuildsQueries, ExplainsQueries, ForwardsCalls, Macroable {
  32. __call as macroCall;
  33. }
  34. /**
  35. * The database connection instance.
  36. *
  37. * @var \Illuminate\Database\ConnectionInterface
  38. */
  39. public $connection;
  40. /**
  41. * The database query grammar instance.
  42. *
  43. * @var \Illuminate\Database\Query\Grammars\Grammar
  44. */
  45. public $grammar;
  46. /**
  47. * The database query post processor instance.
  48. *
  49. * @var \Illuminate\Database\Query\Processors\Processor
  50. */
  51. public $processor;
  52. /**
  53. * The current query value bindings.
  54. *
  55. * @var array
  56. */
  57. public $bindings = [
  58. 'select' => [],
  59. 'from' => [],
  60. 'join' => [],
  61. 'where' => [],
  62. 'groupBy' => [],
  63. 'having' => [],
  64. 'order' => [],
  65. 'union' => [],
  66. 'unionOrder' => [],
  67. ];
  68. /**
  69. * An aggregate function and column to be run.
  70. *
  71. * @var array
  72. */
  73. public $aggregate;
  74. /**
  75. * The columns that should be returned.
  76. *
  77. * @var array|null
  78. */
  79. public $columns;
  80. /**
  81. * Indicates if the query returns distinct results.
  82. *
  83. * Occasionally contains the columns that should be distinct.
  84. *
  85. * @var bool|array
  86. */
  87. public $distinct = false;
  88. /**
  89. * The table which the query is targeting.
  90. *
  91. * @var \Illuminate\Database\Query\Expression|string
  92. */
  93. public $from;
  94. /**
  95. * The index hint for the query.
  96. *
  97. * @var \Illuminate\Database\Query\IndexHint
  98. */
  99. public $indexHint;
  100. /**
  101. * The table joins for the query.
  102. *
  103. * @var array
  104. */
  105. public $joins;
  106. /**
  107. * The where constraints for the query.
  108. *
  109. * @var array
  110. */
  111. public $wheres = [];
  112. /**
  113. * The groupings for the query.
  114. *
  115. * @var array
  116. */
  117. public $groups;
  118. /**
  119. * The having constraints for the query.
  120. *
  121. * @var array
  122. */
  123. public $havings;
  124. /**
  125. * The orderings for the query.
  126. *
  127. * @var array
  128. */
  129. public $orders;
  130. /**
  131. * The maximum number of records to return.
  132. *
  133. * @var int
  134. */
  135. public $limit;
  136. /**
  137. * The maximum number of records to return per group.
  138. *
  139. * @var array
  140. */
  141. public $groupLimit;
  142. /**
  143. * The number of records to skip.
  144. *
  145. * @var int
  146. */
  147. public $offset;
  148. /**
  149. * The query union statements.
  150. *
  151. * @var array
  152. */
  153. public $unions;
  154. /**
  155. * The maximum number of union records to return.
  156. *
  157. * @var int
  158. */
  159. public $unionLimit;
  160. /**
  161. * The number of union records to skip.
  162. *
  163. * @var int
  164. */
  165. public $unionOffset;
  166. /**
  167. * The orderings for the union query.
  168. *
  169. * @var array
  170. */
  171. public $unionOrders;
  172. /**
  173. * Indicates whether row locking is being used.
  174. *
  175. * @var string|bool
  176. */
  177. public $lock;
  178. /**
  179. * The callbacks that should be invoked before the query is executed.
  180. *
  181. * @var array
  182. */
  183. public $beforeQueryCallbacks = [];
  184. /**
  185. * The callbacks that should be invoked after retrieving data from the database.
  186. *
  187. * @var array
  188. */
  189. protected $afterQueryCallbacks = [];
  190. /**
  191. * All of the available clause operators.
  192. *
  193. * @var string[]
  194. */
  195. public $operators = [
  196. '=', '<', '>', '<=', '>=', '<>', '!=', '<=>',
  197. 'like', 'like binary', 'not like', 'ilike',
  198. '&', '|', '^', '<<', '>>', '&~', 'is', 'is not',
  199. 'rlike', 'not rlike', 'regexp', 'not regexp',
  200. '~', '~*', '!~', '!~*', 'similar to',
  201. 'not similar to', 'not ilike', '~~*', '!~~*',
  202. ];
  203. /**
  204. * All of the available bitwise operators.
  205. *
  206. * @var string[]
  207. */
  208. public $bitwiseOperators = [
  209. '&', '|', '^', '<<', '>>', '&~',
  210. ];
  211. /**
  212. * Whether to use write pdo for the select.
  213. *
  214. * @var bool
  215. */
  216. public $useWritePdo = false;
  217. /**
  218. * Create a new query builder instance.
  219. *
  220. * @param \Illuminate\Database\ConnectionInterface $connection
  221. * @param \Illuminate\Database\Query\Grammars\Grammar|null $grammar
  222. * @param \Illuminate\Database\Query\Processors\Processor|null $processor
  223. * @return void
  224. */
  225. public function __construct(ConnectionInterface $connection,
  226. ?Grammar $grammar = null,
  227. ?Processor $processor = null)
  228. {
  229. $this->connection = $connection;
  230. $this->grammar = $grammar ?: $connection->getQueryGrammar();
  231. $this->processor = $processor ?: $connection->getPostProcessor();
  232. }
  233. /**
  234. * Set the columns to be selected.
  235. *
  236. * @param array|mixed $columns
  237. * @return $this
  238. */
  239. public function select($columns = ['*'])
  240. {
  241. $this->columns = [];
  242. $this->bindings['select'] = [];
  243. $columns = is_array($columns) ? $columns : func_get_args();
  244. foreach ($columns as $as => $column) {
  245. if (is_string($as) && $this->isQueryable($column)) {
  246. $this->selectSub($column, $as);
  247. } else {
  248. $this->columns[] = $column;
  249. }
  250. }
  251. return $this;
  252. }
  253. /**
  254. * Add a subselect expression to the query.
  255. *
  256. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  257. * @param string $as
  258. * @return $this
  259. *
  260. * @throws \InvalidArgumentException
  261. */
  262. public function selectSub($query, $as)
  263. {
  264. [$query, $bindings] = $this->createSub($query);
  265. return $this->selectRaw(
  266. '('.$query.') as '.$this->grammar->wrap($as), $bindings
  267. );
  268. }
  269. /**
  270. * Add a new "raw" select expression to the query.
  271. *
  272. * @param string $expression
  273. * @param array $bindings
  274. * @return $this
  275. */
  276. public function selectRaw($expression, array $bindings = [])
  277. {
  278. $this->addSelect(new Expression($expression));
  279. if ($bindings) {
  280. $this->addBinding($bindings, 'select');
  281. }
  282. return $this;
  283. }
  284. /**
  285. * Makes "from" fetch from a subquery.
  286. *
  287. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  288. * @param string $as
  289. * @return $this
  290. *
  291. * @throws \InvalidArgumentException
  292. */
  293. public function fromSub($query, $as)
  294. {
  295. [$query, $bindings] = $this->createSub($query);
  296. return $this->fromRaw('('.$query.') as '.$this->grammar->wrapTable($as), $bindings);
  297. }
  298. /**
  299. * Add a raw from clause to the query.
  300. *
  301. * @param string $expression
  302. * @param mixed $bindings
  303. * @return $this
  304. */
  305. public function fromRaw($expression, $bindings = [])
  306. {
  307. $this->from = new Expression($expression);
  308. $this->addBinding($bindings, 'from');
  309. return $this;
  310. }
  311. /**
  312. * Creates a subquery and parse it.
  313. *
  314. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  315. * @return array
  316. */
  317. protected function createSub($query)
  318. {
  319. // If the given query is a Closure, we will execute it while passing in a new
  320. // query instance to the Closure. This will give the developer a chance to
  321. // format and work with the query before we cast it to a raw SQL string.
  322. if ($query instanceof Closure) {
  323. $callback = $query;
  324. $callback($query = $this->forSubQuery());
  325. }
  326. return $this->parseSub($query);
  327. }
  328. /**
  329. * Parse the subquery into SQL and bindings.
  330. *
  331. * @param mixed $query
  332. * @return array
  333. *
  334. * @throws \InvalidArgumentException
  335. */
  336. protected function parseSub($query)
  337. {
  338. if ($query instanceof self || $query instanceof EloquentBuilder || $query instanceof Relation) {
  339. $query = $this->prependDatabaseNameIfCrossDatabaseQuery($query);
  340. return [$query->toSql(), $query->getBindings()];
  341. } elseif (is_string($query)) {
  342. return [$query, []];
  343. } else {
  344. throw new InvalidArgumentException(
  345. 'A subquery must be a query builder instance, a Closure, or a string.'
  346. );
  347. }
  348. }
  349. /**
  350. * Prepend the database name if the given query is on another database.
  351. *
  352. * @param mixed $query
  353. * @return mixed
  354. */
  355. protected function prependDatabaseNameIfCrossDatabaseQuery($query)
  356. {
  357. if ($query->getConnection()->getDatabaseName() !==
  358. $this->getConnection()->getDatabaseName()) {
  359. $databaseName = $query->getConnection()->getDatabaseName();
  360. if (! str_starts_with($query->from, $databaseName) && ! str_contains($query->from, '.')) {
  361. $query->from($databaseName.'.'.$query->from);
  362. }
  363. }
  364. return $query;
  365. }
  366. /**
  367. * Add a new select column to the query.
  368. *
  369. * @param array|mixed $column
  370. * @return $this
  371. */
  372. public function addSelect($column)
  373. {
  374. $columns = is_array($column) ? $column : func_get_args();
  375. foreach ($columns as $as => $column) {
  376. if (is_string($as) && $this->isQueryable($column)) {
  377. if (is_null($this->columns)) {
  378. $this->select($this->from.'.*');
  379. }
  380. $this->selectSub($column, $as);
  381. } else {
  382. if (is_array($this->columns) && in_array($column, $this->columns, true)) {
  383. continue;
  384. }
  385. $this->columns[] = $column;
  386. }
  387. }
  388. return $this;
  389. }
  390. /**
  391. * Force the query to only return distinct results.
  392. *
  393. * @return $this
  394. */
  395. public function distinct()
  396. {
  397. $columns = func_get_args();
  398. if (count($columns) > 0) {
  399. $this->distinct = is_array($columns[0]) || is_bool($columns[0]) ? $columns[0] : $columns;
  400. } else {
  401. $this->distinct = true;
  402. }
  403. return $this;
  404. }
  405. /**
  406. * Set the table which the query is targeting.
  407. *
  408. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Contracts\Database\Query\Expression|string $table
  409. * @param string|null $as
  410. * @return $this
  411. */
  412. public function from($table, $as = null)
  413. {
  414. if ($this->isQueryable($table)) {
  415. return $this->fromSub($table, $as);
  416. }
  417. $this->from = $as ? "{$table} as {$as}" : $table;
  418. return $this;
  419. }
  420. /**
  421. * Add an index hint to suggest a query index.
  422. *
  423. * @param string $index
  424. * @return $this
  425. */
  426. public function useIndex($index)
  427. {
  428. $this->indexHint = new IndexHint('hint', $index);
  429. return $this;
  430. }
  431. /**
  432. * Add an index hint to force a query index.
  433. *
  434. * @param string $index
  435. * @return $this
  436. */
  437. public function forceIndex($index)
  438. {
  439. $this->indexHint = new IndexHint('force', $index);
  440. return $this;
  441. }
  442. /**
  443. * Add an index hint to ignore a query index.
  444. *
  445. * @param string $index
  446. * @return $this
  447. */
  448. public function ignoreIndex($index)
  449. {
  450. $this->indexHint = new IndexHint('ignore', $index);
  451. return $this;
  452. }
  453. /**
  454. * Add a join clause to the query.
  455. *
  456. * @param \Illuminate\Contracts\Database\Query\Expression|string $table
  457. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
  458. * @param string|null $operator
  459. * @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
  460. * @param string $type
  461. * @param bool $where
  462. * @return $this
  463. */
  464. public function join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false)
  465. {
  466. $join = $this->newJoinClause($this, $type, $table);
  467. // If the first "column" of the join is really a Closure instance the developer
  468. // is trying to build a join with a complex "on" clause containing more than
  469. // one condition, so we'll add the join and call a Closure with the query.
  470. if ($first instanceof Closure) {
  471. $first($join);
  472. $this->joins[] = $join;
  473. $this->addBinding($join->getBindings(), 'join');
  474. }
  475. // If the column is simply a string, we can assume the join simply has a basic
  476. // "on" clause with a single condition. So we will just build the join with
  477. // this simple join clauses attached to it. There is not a join callback.
  478. else {
  479. $method = $where ? 'where' : 'on';
  480. $this->joins[] = $join->$method($first, $operator, $second);
  481. $this->addBinding($join->getBindings(), 'join');
  482. }
  483. return $this;
  484. }
  485. /**
  486. * Add a "join where" clause to the query.
  487. *
  488. * @param \Illuminate\Contracts\Database\Query\Expression|string $table
  489. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
  490. * @param string $operator
  491. * @param \Illuminate\Contracts\Database\Query\Expression|string $second
  492. * @param string $type
  493. * @return $this
  494. */
  495. public function joinWhere($table, $first, $operator, $second, $type = 'inner')
  496. {
  497. return $this->join($table, $first, $operator, $second, $type, true);
  498. }
  499. /**
  500. * Add a subquery join clause to the query.
  501. *
  502. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  503. * @param string $as
  504. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
  505. * @param string|null $operator
  506. * @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
  507. * @param string $type
  508. * @param bool $where
  509. * @return $this
  510. *
  511. * @throws \InvalidArgumentException
  512. */
  513. public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)
  514. {
  515. [$query, $bindings] = $this->createSub($query);
  516. $expression = '('.$query.') as '.$this->grammar->wrapTable($as);
  517. $this->addBinding($bindings, 'join');
  518. return $this->join(new Expression($expression), $first, $operator, $second, $type, $where);
  519. }
  520. /**
  521. * Add a lateral join clause to the query.
  522. *
  523. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  524. * @param string $as
  525. * @param string $type
  526. * @return $this
  527. */
  528. public function joinLateral($query, string $as, string $type = 'inner')
  529. {
  530. [$query, $bindings] = $this->createSub($query);
  531. $expression = '('.$query.') as '.$this->grammar->wrapTable($as);
  532. $this->addBinding($bindings, 'join');
  533. $this->joins[] = $this->newJoinLateralClause($this, $type, new Expression($expression));
  534. return $this;
  535. }
  536. /**
  537. * Add a lateral left join to the query.
  538. *
  539. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  540. * @param string $as
  541. * @return $this
  542. */
  543. public function leftJoinLateral($query, string $as)
  544. {
  545. return $this->joinLateral($query, $as, 'left');
  546. }
  547. /**
  548. * Add a left join to the query.
  549. *
  550. * @param \Illuminate\Contracts\Database\Query\Expression|string $table
  551. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
  552. * @param string|null $operator
  553. * @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
  554. * @return $this
  555. */
  556. public function leftJoin($table, $first, $operator = null, $second = null)
  557. {
  558. return $this->join($table, $first, $operator, $second, 'left');
  559. }
  560. /**
  561. * Add a "join where" clause to the query.
  562. *
  563. * @param \Illuminate\Contracts\Database\Query\Expression|string $table
  564. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
  565. * @param string $operator
  566. * @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
  567. * @return $this
  568. */
  569. public function leftJoinWhere($table, $first, $operator, $second)
  570. {
  571. return $this->joinWhere($table, $first, $operator, $second, 'left');
  572. }
  573. /**
  574. * Add a subquery left join to the query.
  575. *
  576. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  577. * @param string $as
  578. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
  579. * @param string|null $operator
  580. * @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
  581. * @return $this
  582. */
  583. public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
  584. {
  585. return $this->joinSub($query, $as, $first, $operator, $second, 'left');
  586. }
  587. /**
  588. * Add a right join to the query.
  589. *
  590. * @param \Illuminate\Contracts\Database\Query\Expression|string $table
  591. * @param \Closure|string $first
  592. * @param string|null $operator
  593. * @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
  594. * @return $this
  595. */
  596. public function rightJoin($table, $first, $operator = null, $second = null)
  597. {
  598. return $this->join($table, $first, $operator, $second, 'right');
  599. }
  600. /**
  601. * Add a "right join where" clause to the query.
  602. *
  603. * @param \Illuminate\Contracts\Database\Query\Expression|string $table
  604. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
  605. * @param string $operator
  606. * @param \Illuminate\Contracts\Database\Query\Expression|string $second
  607. * @return $this
  608. */
  609. public function rightJoinWhere($table, $first, $operator, $second)
  610. {
  611. return $this->joinWhere($table, $first, $operator, $second, 'right');
  612. }
  613. /**
  614. * Add a subquery right join to the query.
  615. *
  616. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  617. * @param string $as
  618. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string $first
  619. * @param string|null $operator
  620. * @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
  621. * @return $this
  622. */
  623. public function rightJoinSub($query, $as, $first, $operator = null, $second = null)
  624. {
  625. return $this->joinSub($query, $as, $first, $operator, $second, 'right');
  626. }
  627. /**
  628. * Add a "cross join" clause to the query.
  629. *
  630. * @param \Illuminate\Contracts\Database\Query\Expression|string $table
  631. * @param \Closure|\Illuminate\Contracts\Database\Query\Expression|string|null $first
  632. * @param string|null $operator
  633. * @param \Illuminate\Contracts\Database\Query\Expression|string|null $second
  634. * @return $this
  635. */
  636. public function crossJoin($table, $first = null, $operator = null, $second = null)
  637. {
  638. if ($first) {
  639. return $this->join($table, $first, $operator, $second, 'cross');
  640. }
  641. $this->joins[] = $this->newJoinClause($this, 'cross', $table);
  642. return $this;
  643. }
  644. /**
  645. * Add a subquery cross join to the query.
  646. *
  647. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  648. * @param string $as
  649. * @return $this
  650. */
  651. public function crossJoinSub($query, $as)
  652. {
  653. [$query, $bindings] = $this->createSub($query);
  654. $expression = '('.$query.') as '.$this->grammar->wrapTable($as);
  655. $this->addBinding($bindings, 'join');
  656. $this->joins[] = $this->newJoinClause($this, 'cross', new Expression($expression));
  657. return $this;
  658. }
  659. /**
  660. * Get a new join clause.
  661. *
  662. * @param \Illuminate\Database\Query\Builder $parentQuery
  663. * @param string $type
  664. * @param string $table
  665. * @return \Illuminate\Database\Query\JoinClause
  666. */
  667. protected function newJoinClause(self $parentQuery, $type, $table)
  668. {
  669. return new JoinClause($parentQuery, $type, $table);
  670. }
  671. /**
  672. * Get a new join lateral clause.
  673. *
  674. * @param \Illuminate\Database\Query\Builder $parentQuery
  675. * @param string $type
  676. * @param string $table
  677. * @return \Illuminate\Database\Query\JoinLateralClause
  678. */
  679. protected function newJoinLateralClause(self $parentQuery, $type, $table)
  680. {
  681. return new JoinLateralClause($parentQuery, $type, $table);
  682. }
  683. /**
  684. * Merge an array of where clauses and bindings.
  685. *
  686. * @param array $wheres
  687. * @param array $bindings
  688. * @return $this
  689. */
  690. public function mergeWheres($wheres, $bindings)
  691. {
  692. $this->wheres = array_merge($this->wheres, (array) $wheres);
  693. $this->bindings['where'] = array_values(
  694. array_merge($this->bindings['where'], (array) $bindings)
  695. );
  696. return $this;
  697. }
  698. /**
  699. * Add a basic where clause to the query.
  700. *
  701. * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column
  702. * @param mixed $operator
  703. * @param mixed $value
  704. * @param string $boolean
  705. * @return $this
  706. */
  707. public function where($column, $operator = null, $value = null, $boolean = 'and')
  708. {
  709. if ($column instanceof ConditionExpression) {
  710. $type = 'Expression';
  711. $this->wheres[] = compact('type', 'column', 'boolean');
  712. return $this;
  713. }
  714. // If the column is an array, we will assume it is an array of key-value pairs
  715. // and can add them each as a where clause. We will maintain the boolean we
  716. // received when the method was called and pass it into the nested where.
  717. if (is_array($column)) {
  718. return $this->addArrayOfWheres($column, $boolean);
  719. }
  720. // Here we will make some assumptions about the operator. If only 2 values are
  721. // passed to the method, we will assume that the operator is an equals sign
  722. // and keep going. Otherwise, we'll require the operator to be passed in.
  723. [$value, $operator] = $this->prepareValueAndOperator(
  724. $value, $operator, func_num_args() === 2
  725. );
  726. // If the column is actually a Closure instance, we will assume the developer
  727. // wants to begin a nested where statement which is wrapped in parentheses.
  728. // We will add that Closure to the query and return back out immediately.
  729. if ($column instanceof Closure && is_null($operator)) {
  730. return $this->whereNested($column, $boolean);
  731. }
  732. // If the column is a Closure instance and there is an operator value, we will
  733. // assume the developer wants to run a subquery and then compare the result
  734. // of that subquery with the given value that was provided to the method.
  735. if ($this->isQueryable($column) && ! is_null($operator)) {
  736. [$sub, $bindings] = $this->createSub($column);
  737. return $this->addBinding($bindings, 'where')
  738. ->where(new Expression('('.$sub.')'), $operator, $value, $boolean);
  739. }
  740. // If the given operator is not found in the list of valid operators we will
  741. // assume that the developer is just short-cutting the '=' operators and
  742. // we will set the operators to '=' and set the values appropriately.
  743. if ($this->invalidOperator($operator)) {
  744. [$value, $operator] = [$operator, '='];
  745. }
  746. // If the value is a Closure, it means the developer is performing an entire
  747. // sub-select within the query and we will need to compile the sub-select
  748. // within the where clause to get the appropriate query record results.
  749. if ($this->isQueryable($value)) {
  750. return $this->whereSub($column, $operator, $value, $boolean);
  751. }
  752. // If the value is "null", we will just assume the developer wants to add a
  753. // where null clause to the query. So, we will allow a short-cut here to
  754. // that method for convenience so the developer doesn't have to check.
  755. if (is_null($value)) {
  756. return $this->whereNull($column, $boolean, $operator !== '=');
  757. }
  758. $type = 'Basic';
  759. $columnString = ($column instanceof ExpressionContract)
  760. ? $this->grammar->getValue($column)
  761. : $column;
  762. // If the column is making a JSON reference we'll check to see if the value
  763. // is a boolean. If it is, we'll add the raw boolean string as an actual
  764. // value to the query to ensure this is properly handled by the query.
  765. if (str_contains($columnString, '->') && is_bool($value)) {
  766. $value = new Expression($value ? 'true' : 'false');
  767. if (is_string($column)) {
  768. $type = 'JsonBoolean';
  769. }
  770. }
  771. if ($this->isBitwiseOperator($operator)) {
  772. $type = 'Bitwise';
  773. }
  774. // Now that we are working with just a simple query we can put the elements
  775. // in our array and add the query binding to our array of bindings that
  776. // will be bound to each SQL statements when it is finally executed.
  777. $this->wheres[] = compact(
  778. 'type', 'column', 'operator', 'value', 'boolean'
  779. );
  780. if (! $value instanceof ExpressionContract) {
  781. $this->addBinding($this->flattenValue($value), 'where');
  782. }
  783. return $this;
  784. }
  785. /**
  786. * Add an array of where clauses to the query.
  787. *
  788. * @param array $column
  789. * @param string $boolean
  790. * @param string $method
  791. * @return $this
  792. */
  793. protected function addArrayOfWheres($column, $boolean, $method = 'where')
  794. {
  795. return $this->whereNested(function ($query) use ($column, $method, $boolean) {
  796. foreach ($column as $key => $value) {
  797. if (is_numeric($key) && is_array($value)) {
  798. $query->{$method}(...array_values($value));
  799. } else {
  800. $query->{$method}($key, '=', $value, $boolean);
  801. }
  802. }
  803. }, $boolean);
  804. }
  805. /**
  806. * Prepare the value and operator for a where clause.
  807. *
  808. * @param string $value
  809. * @param string $operator
  810. * @param bool $useDefault
  811. * @return array
  812. *
  813. * @throws \InvalidArgumentException
  814. */
  815. public function prepareValueAndOperator($value, $operator, $useDefault = false)
  816. {
  817. if ($useDefault) {
  818. return [$operator, '='];
  819. } elseif ($this->invalidOperatorAndValue($operator, $value)) {
  820. throw new InvalidArgumentException('Illegal operator and value combination.');
  821. }
  822. return [$value, $operator];
  823. }
  824. /**
  825. * Determine if the given operator and value combination is legal.
  826. *
  827. * Prevents using Null values with invalid operators.
  828. *
  829. * @param string $operator
  830. * @param mixed $value
  831. * @return bool
  832. */
  833. protected function invalidOperatorAndValue($operator, $value)
  834. {
  835. return is_null($value) && in_array($operator, $this->operators) &&
  836. ! in_array($operator, ['=', '<>', '!=']);
  837. }
  838. /**
  839. * Determine if the given operator is supported.
  840. *
  841. * @param string $operator
  842. * @return bool
  843. */
  844. protected function invalidOperator($operator)
  845. {
  846. return ! is_string($operator) || (! in_array(strtolower($operator), $this->operators, true) &&
  847. ! in_array(strtolower($operator), $this->grammar->getOperators(), true));
  848. }
  849. /**
  850. * Determine if the operator is a bitwise operator.
  851. *
  852. * @param string $operator
  853. * @return bool
  854. */
  855. protected function isBitwiseOperator($operator)
  856. {
  857. return in_array(strtolower($operator), $this->bitwiseOperators, true) ||
  858. in_array(strtolower($operator), $this->grammar->getBitwiseOperators(), true);
  859. }
  860. /**
  861. * Add an "or where" clause to the query.
  862. *
  863. * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column
  864. * @param mixed $operator
  865. * @param mixed $value
  866. * @return $this
  867. */
  868. public function orWhere($column, $operator = null, $value = null)
  869. {
  870. [$value, $operator] = $this->prepareValueAndOperator(
  871. $value, $operator, func_num_args() === 2
  872. );
  873. return $this->where($column, $operator, $value, 'or');
  874. }
  875. /**
  876. * Add a basic "where not" clause to the query.
  877. *
  878. * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column
  879. * @param mixed $operator
  880. * @param mixed $value
  881. * @param string $boolean
  882. * @return $this
  883. */
  884. public function whereNot($column, $operator = null, $value = null, $boolean = 'and')
  885. {
  886. if (is_array($column)) {
  887. return $this->whereNested(function ($query) use ($column, $operator, $value, $boolean) {
  888. $query->where($column, $operator, $value, $boolean);
  889. }, $boolean.' not');
  890. }
  891. return $this->where($column, $operator, $value, $boolean.' not');
  892. }
  893. /**
  894. * Add an "or where not" clause to the query.
  895. *
  896. * @param \Closure|string|array|\Illuminate\Contracts\Database\Query\Expression $column
  897. * @param mixed $operator
  898. * @param mixed $value
  899. * @return $this
  900. */
  901. public function orWhereNot($column, $operator = null, $value = null)
  902. {
  903. return $this->whereNot($column, $operator, $value, 'or');
  904. }
  905. /**
  906. * Add a "where" clause comparing two columns to the query.
  907. *
  908. * @param \Illuminate\Contracts\Database\Query\Expression|string|array $first
  909. * @param string|null $operator
  910. * @param string|null $second
  911. * @param string|null $boolean
  912. * @return $this
  913. */
  914. public function whereColumn($first, $operator = null, $second = null, $boolean = 'and')
  915. {
  916. // If the column is an array, we will assume it is an array of key-value pairs
  917. // and can add them each as a where clause. We will maintain the boolean we
  918. // received when the method was called and pass it into the nested where.
  919. if (is_array($first)) {
  920. return $this->addArrayOfWheres($first, $boolean, 'whereColumn');
  921. }
  922. // If the given operator is not found in the list of valid operators we will
  923. // assume that the developer is just short-cutting the '=' operators and
  924. // we will set the operators to '=' and set the values appropriately.
  925. if ($this->invalidOperator($operator)) {
  926. [$second, $operator] = [$operator, '='];
  927. }
  928. // Finally, we will add this where clause into this array of clauses that we
  929. // are building for the query. All of them will be compiled via a grammar
  930. // once the query is about to be executed and run against the database.
  931. $type = 'Column';
  932. $this->wheres[] = compact(
  933. 'type', 'first', 'operator', 'second', 'boolean'
  934. );
  935. return $this;
  936. }
  937. /**
  938. * Add an "or where" clause comparing two columns to the query.
  939. *
  940. * @param \Illuminate\Contracts\Database\Query\Expression|string|array $first
  941. * @param string|null $operator
  942. * @param string|null $second
  943. * @return $this
  944. */
  945. public function orWhereColumn($first, $operator = null, $second = null)
  946. {
  947. return $this->whereColumn($first, $operator, $second, 'or');
  948. }
  949. /**
  950. * Add a raw where clause to the query.
  951. *
  952. * @param string $sql
  953. * @param mixed $bindings
  954. * @param string $boolean
  955. * @return $this
  956. */
  957. public function whereRaw($sql, $bindings = [], $boolean = 'and')
  958. {
  959. $this->wheres[] = ['type' => 'raw', 'sql' => $sql, 'boolean' => $boolean];
  960. $this->addBinding((array) $bindings, 'where');
  961. return $this;
  962. }
  963. /**
  964. * Add a raw or where clause to the query.
  965. *
  966. * @param string $sql
  967. * @param mixed $bindings
  968. * @return $this
  969. */
  970. public function orWhereRaw($sql, $bindings = [])
  971. {
  972. return $this->whereRaw($sql, $bindings, 'or');
  973. }
  974. /**
  975. * Add a "where in" clause to the query.
  976. *
  977. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  978. * @param mixed $values
  979. * @param string $boolean
  980. * @param bool $not
  981. * @return $this
  982. */
  983. public function whereIn($column, $values, $boolean = 'and', $not = false)
  984. {
  985. $type = $not ? 'NotIn' : 'In';
  986. // If the value is a query builder instance we will assume the developer wants to
  987. // look for any values that exist within this given query. So, we will add the
  988. // query accordingly so that this query is properly executed when it is run.
  989. if ($this->isQueryable($values)) {
  990. [$query, $bindings] = $this->createSub($values);
  991. $values = [new Expression($query)];
  992. $this->addBinding($bindings, 'where');
  993. }
  994. // Next, if the value is Arrayable we need to cast it to its raw array form so we
  995. // have the underlying array value instead of an Arrayable object which is not
  996. // able to be added as a binding, etc. We will then add to the wheres array.
  997. if ($values instanceof Arrayable) {
  998. $values = $values->toArray();
  999. }
  1000. $this->wheres[] = compact('type', 'column', 'values', 'boolean');
  1001. if (count($values) !== count(Arr::flatten($values, 1))) {
  1002. throw new InvalidArgumentException('Nested arrays may not be passed to whereIn method.');
  1003. }
  1004. // Finally, we'll add a binding for each value unless that value is an expression
  1005. // in which case we will just skip over it since it will be the query as a raw
  1006. // string and not as a parameterized place-holder to be replaced by the PDO.
  1007. $this->addBinding($this->cleanBindings($values), 'where');
  1008. return $this;
  1009. }
  1010. /**
  1011. * Add an "or where in" clause to the query.
  1012. *
  1013. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1014. * @param mixed $values
  1015. * @return $this
  1016. */
  1017. public function orWhereIn($column, $values)
  1018. {
  1019. return $this->whereIn($column, $values, 'or');
  1020. }
  1021. /**
  1022. * Add a "where not in" clause to the query.
  1023. *
  1024. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1025. * @param mixed $values
  1026. * @param string $boolean
  1027. * @return $this
  1028. */
  1029. public function whereNotIn($column, $values, $boolean = 'and')
  1030. {
  1031. return $this->whereIn($column, $values, $boolean, true);
  1032. }
  1033. /**
  1034. * Add an "or where not in" clause to the query.
  1035. *
  1036. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1037. * @param mixed $values
  1038. * @return $this
  1039. */
  1040. public function orWhereNotIn($column, $values)
  1041. {
  1042. return $this->whereNotIn($column, $values, 'or');
  1043. }
  1044. /**
  1045. * Add a "where in raw" clause for integer values to the query.
  1046. *
  1047. * @param string $column
  1048. * @param \Illuminate\Contracts\Support\Arrayable|array $values
  1049. * @param string $boolean
  1050. * @param bool $not
  1051. * @return $this
  1052. */
  1053. public function whereIntegerInRaw($column, $values, $boolean = 'and', $not = false)
  1054. {
  1055. $type = $not ? 'NotInRaw' : 'InRaw';
  1056. if ($values instanceof Arrayable) {
  1057. $values = $values->toArray();
  1058. }
  1059. $values = Arr::flatten($values);
  1060. foreach ($values as &$value) {
  1061. $value = (int) ($value instanceof BackedEnum ? $value->value : $value);
  1062. }
  1063. $this->wheres[] = compact('type', 'column', 'values', 'boolean');
  1064. return $this;
  1065. }
  1066. /**
  1067. * Add an "or where in raw" clause for integer values to the query.
  1068. *
  1069. * @param string $column
  1070. * @param \Illuminate\Contracts\Support\Arrayable|array $values
  1071. * @return $this
  1072. */
  1073. public function orWhereIntegerInRaw($column, $values)
  1074. {
  1075. return $this->whereIntegerInRaw($column, $values, 'or');
  1076. }
  1077. /**
  1078. * Add a "where not in raw" clause for integer values to the query.
  1079. *
  1080. * @param string $column
  1081. * @param \Illuminate\Contracts\Support\Arrayable|array $values
  1082. * @param string $boolean
  1083. * @return $this
  1084. */
  1085. public function whereIntegerNotInRaw($column, $values, $boolean = 'and')
  1086. {
  1087. return $this->whereIntegerInRaw($column, $values, $boolean, true);
  1088. }
  1089. /**
  1090. * Add an "or where not in raw" clause for integer values to the query.
  1091. *
  1092. * @param string $column
  1093. * @param \Illuminate\Contracts\Support\Arrayable|array $values
  1094. * @return $this
  1095. */
  1096. public function orWhereIntegerNotInRaw($column, $values)
  1097. {
  1098. return $this->whereIntegerNotInRaw($column, $values, 'or');
  1099. }
  1100. /**
  1101. * Add a "where null" clause to the query.
  1102. *
  1103. * @param string|array|\Illuminate\Contracts\Database\Query\Expression $columns
  1104. * @param string $boolean
  1105. * @param bool $not
  1106. * @return $this
  1107. */
  1108. public function whereNull($columns, $boolean = 'and', $not = false)
  1109. {
  1110. $type = $not ? 'NotNull' : 'Null';
  1111. foreach (Arr::wrap($columns) as $column) {
  1112. $this->wheres[] = compact('type', 'column', 'boolean');
  1113. }
  1114. return $this;
  1115. }
  1116. /**
  1117. * Add an "or where null" clause to the query.
  1118. *
  1119. * @param string|array|\Illuminate\Contracts\Database\Query\Expression $column
  1120. * @return $this
  1121. */
  1122. public function orWhereNull($column)
  1123. {
  1124. return $this->whereNull($column, 'or');
  1125. }
  1126. /**
  1127. * Add a "where not null" clause to the query.
  1128. *
  1129. * @param string|array|\Illuminate\Contracts\Database\Query\Expression $columns
  1130. * @param string $boolean
  1131. * @return $this
  1132. */
  1133. public function whereNotNull($columns, $boolean = 'and')
  1134. {
  1135. return $this->whereNull($columns, $boolean, true);
  1136. }
  1137. /**
  1138. * Add a where between statement to the query.
  1139. *
  1140. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1141. * @param iterable $values
  1142. * @param string $boolean
  1143. * @param bool $not
  1144. * @return $this
  1145. */
  1146. public function whereBetween($column, iterable $values, $boolean = 'and', $not = false)
  1147. {
  1148. $type = 'between';
  1149. if ($values instanceof CarbonPeriod) {
  1150. $values = [$values->getStartDate(), $values->getEndDate()];
  1151. }
  1152. $this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not');
  1153. $this->addBinding(array_slice($this->cleanBindings(Arr::flatten($values)), 0, 2), 'where');
  1154. return $this;
  1155. }
  1156. /**
  1157. * Add a where between statement using columns to the query.
  1158. *
  1159. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1160. * @param array $values
  1161. * @param string $boolean
  1162. * @param bool $not
  1163. * @return $this
  1164. */
  1165. public function whereBetweenColumns($column, array $values, $boolean = 'and', $not = false)
  1166. {
  1167. $type = 'betweenColumns';
  1168. $this->wheres[] = compact('type', 'column', 'values', 'boolean', 'not');
  1169. return $this;
  1170. }
  1171. /**
  1172. * Add an or where between statement to the query.
  1173. *
  1174. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1175. * @param iterable $values
  1176. * @return $this
  1177. */
  1178. public function orWhereBetween($column, iterable $values)
  1179. {
  1180. return $this->whereBetween($column, $values, 'or');
  1181. }
  1182. /**
  1183. * Add an or where between statement using columns to the query.
  1184. *
  1185. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1186. * @param array $values
  1187. * @return $this
  1188. */
  1189. public function orWhereBetweenColumns($column, array $values)
  1190. {
  1191. return $this->whereBetweenColumns($column, $values, 'or');
  1192. }
  1193. /**
  1194. * Add a where not between statement to the query.
  1195. *
  1196. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1197. * @param iterable $values
  1198. * @param string $boolean
  1199. * @return $this
  1200. */
  1201. public function whereNotBetween($column, iterable $values, $boolean = 'and')
  1202. {
  1203. return $this->whereBetween($column, $values, $boolean, true);
  1204. }
  1205. /**
  1206. * Add a where not between statement using columns to the query.
  1207. *
  1208. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1209. * @param array $values
  1210. * @param string $boolean
  1211. * @return $this
  1212. */
  1213. public function whereNotBetweenColumns($column, array $values, $boolean = 'and')
  1214. {
  1215. return $this->whereBetweenColumns($column, $values, $boolean, true);
  1216. }
  1217. /**
  1218. * Add an or where not between statement to the query.
  1219. *
  1220. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1221. * @param iterable $values
  1222. * @return $this
  1223. */
  1224. public function orWhereNotBetween($column, iterable $values)
  1225. {
  1226. return $this->whereNotBetween($column, $values, 'or');
  1227. }
  1228. /**
  1229. * Add an or where not between statement using columns to the query.
  1230. *
  1231. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1232. * @param array $values
  1233. * @return $this
  1234. */
  1235. public function orWhereNotBetweenColumns($column, array $values)
  1236. {
  1237. return $this->whereNotBetweenColumns($column, $values, 'or');
  1238. }
  1239. /**
  1240. * Add an "or where not null" clause to the query.
  1241. *
  1242. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1243. * @return $this
  1244. */
  1245. public function orWhereNotNull($column)
  1246. {
  1247. return $this->whereNotNull($column, 'or');
  1248. }
  1249. /**
  1250. * Add a "where date" statement to the query.
  1251. *
  1252. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1253. * @param \DateTimeInterface|string|null $operator
  1254. * @param \DateTimeInterface|string|null $value
  1255. * @param string $boolean
  1256. * @return $this
  1257. */
  1258. public function whereDate($column, $operator, $value = null, $boolean = 'and')
  1259. {
  1260. [$value, $operator] = $this->prepareValueAndOperator(
  1261. $value, $operator, func_num_args() === 2
  1262. );
  1263. $value = $this->flattenValue($value);
  1264. if ($value instanceof DateTimeInterface) {
  1265. $value = $value->format('Y-m-d');
  1266. }
  1267. return $this->addDateBasedWhere('Date', $column, $operator, $value, $boolean);
  1268. }
  1269. /**
  1270. * Add an "or where date" statement to the query.
  1271. *
  1272. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1273. * @param \DateTimeInterface|string|null $operator
  1274. * @param \DateTimeInterface|string|null $value
  1275. * @return $this
  1276. */
  1277. public function orWhereDate($column, $operator, $value = null)
  1278. {
  1279. [$value, $operator] = $this->prepareValueAndOperator(
  1280. $value, $operator, func_num_args() === 2
  1281. );
  1282. return $this->whereDate($column, $operator, $value, 'or');
  1283. }
  1284. /**
  1285. * Add a "where time" statement to the query.
  1286. *
  1287. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1288. * @param \DateTimeInterface|string|null $operator
  1289. * @param \DateTimeInterface|string|null $value
  1290. * @param string $boolean
  1291. * @return $this
  1292. */
  1293. public function whereTime($column, $operator, $value = null, $boolean = 'and')
  1294. {
  1295. [$value, $operator] = $this->prepareValueAndOperator(
  1296. $value, $operator, func_num_args() === 2
  1297. );
  1298. $value = $this->flattenValue($value);
  1299. if ($value instanceof DateTimeInterface) {
  1300. $value = $value->format('H:i:s');
  1301. }
  1302. return $this->addDateBasedWhere('Time', $column, $operator, $value, $boolean);
  1303. }
  1304. /**
  1305. * Add an "or where time" statement to the query.
  1306. *
  1307. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1308. * @param \DateTimeInterface|string|null $operator
  1309. * @param \DateTimeInterface|string|null $value
  1310. * @return $this
  1311. */
  1312. public function orWhereTime($column, $operator, $value = null)
  1313. {
  1314. [$value, $operator] = $this->prepareValueAndOperator(
  1315. $value, $operator, func_num_args() === 2
  1316. );
  1317. return $this->whereTime($column, $operator, $value, 'or');
  1318. }
  1319. /**
  1320. * Add a "where day" statement to the query.
  1321. *
  1322. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1323. * @param \DateTimeInterface|string|int|null $operator
  1324. * @param \DateTimeInterface|string|int|null $value
  1325. * @param string $boolean
  1326. * @return $this
  1327. */
  1328. public function whereDay($column, $operator, $value = null, $boolean = 'and')
  1329. {
  1330. [$value, $operator] = $this->prepareValueAndOperator(
  1331. $value, $operator, func_num_args() === 2
  1332. );
  1333. $value = $this->flattenValue($value);
  1334. if ($value instanceof DateTimeInterface) {
  1335. $value = $value->format('d');
  1336. }
  1337. if (! $value instanceof ExpressionContract) {
  1338. $value = sprintf('%02d', $value);
  1339. }
  1340. return $this->addDateBasedWhere('Day', $column, $operator, $value, $boolean);
  1341. }
  1342. /**
  1343. * Add an "or where day" statement to the query.
  1344. *
  1345. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1346. * @param \DateTimeInterface|string|int|null $operator
  1347. * @param \DateTimeInterface|string|int|null $value
  1348. * @return $this
  1349. */
  1350. public function orWhereDay($column, $operator, $value = null)
  1351. {
  1352. [$value, $operator] = $this->prepareValueAndOperator(
  1353. $value, $operator, func_num_args() === 2
  1354. );
  1355. return $this->whereDay($column, $operator, $value, 'or');
  1356. }
  1357. /**
  1358. * Add a "where month" statement to the query.
  1359. *
  1360. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1361. * @param \DateTimeInterface|string|int|null $operator
  1362. * @param \DateTimeInterface|string|int|null $value
  1363. * @param string $boolean
  1364. * @return $this
  1365. */
  1366. public function whereMonth($column, $operator, $value = null, $boolean = 'and')
  1367. {
  1368. [$value, $operator] = $this->prepareValueAndOperator(
  1369. $value, $operator, func_num_args() === 2
  1370. );
  1371. $value = $this->flattenValue($value);
  1372. if ($value instanceof DateTimeInterface) {
  1373. $value = $value->format('m');
  1374. }
  1375. if (! $value instanceof ExpressionContract) {
  1376. $value = sprintf('%02d', $value);
  1377. }
  1378. return $this->addDateBasedWhere('Month', $column, $operator, $value, $boolean);
  1379. }
  1380. /**
  1381. * Add an "or where month" statement to the query.
  1382. *
  1383. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1384. * @param \DateTimeInterface|string|int|null $operator
  1385. * @param \DateTimeInterface|string|int|null $value
  1386. * @return $this
  1387. */
  1388. public function orWhereMonth($column, $operator, $value = null)
  1389. {
  1390. [$value, $operator] = $this->prepareValueAndOperator(
  1391. $value, $operator, func_num_args() === 2
  1392. );
  1393. return $this->whereMonth($column, $operator, $value, 'or');
  1394. }
  1395. /**
  1396. * Add a "where year" statement to the query.
  1397. *
  1398. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1399. * @param \DateTimeInterface|string|int|null $operator
  1400. * @param \DateTimeInterface|string|int|null $value
  1401. * @param string $boolean
  1402. * @return $this
  1403. */
  1404. public function whereYear($column, $operator, $value = null, $boolean = 'and')
  1405. {
  1406. [$value, $operator] = $this->prepareValueAndOperator(
  1407. $value, $operator, func_num_args() === 2
  1408. );
  1409. $value = $this->flattenValue($value);
  1410. if ($value instanceof DateTimeInterface) {
  1411. $value = $value->format('Y');
  1412. }
  1413. return $this->addDateBasedWhere('Year', $column, $operator, $value, $boolean);
  1414. }
  1415. /**
  1416. * Add an "or where year" statement to the query.
  1417. *
  1418. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1419. * @param \DateTimeInterface|string|int|null $operator
  1420. * @param \DateTimeInterface|string|int|null $value
  1421. * @return $this
  1422. */
  1423. public function orWhereYear($column, $operator, $value = null)
  1424. {
  1425. [$value, $operator] = $this->prepareValueAndOperator(
  1426. $value, $operator, func_num_args() === 2
  1427. );
  1428. return $this->whereYear($column, $operator, $value, 'or');
  1429. }
  1430. /**
  1431. * Add a date based (year, month, day, time) statement to the query.
  1432. *
  1433. * @param string $type
  1434. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1435. * @param string $operator
  1436. * @param mixed $value
  1437. * @param string $boolean
  1438. * @return $this
  1439. */
  1440. protected function addDateBasedWhere($type, $column, $operator, $value, $boolean = 'and')
  1441. {
  1442. $this->wheres[] = compact('column', 'type', 'boolean', 'operator', 'value');
  1443. if (! $value instanceof ExpressionContract) {
  1444. $this->addBinding($value, 'where');
  1445. }
  1446. return $this;
  1447. }
  1448. /**
  1449. * Add a nested where statement to the query.
  1450. *
  1451. * @param \Closure $callback
  1452. * @param string $boolean
  1453. * @return $this
  1454. */
  1455. public function whereNested(Closure $callback, $boolean = 'and')
  1456. {
  1457. $callback($query = $this->forNestedWhere());
  1458. return $this->addNestedWhereQuery($query, $boolean);
  1459. }
  1460. /**
  1461. * Create a new query instance for nested where condition.
  1462. *
  1463. * @return \Illuminate\Database\Query\Builder
  1464. */
  1465. public function forNestedWhere()
  1466. {
  1467. return $this->newQuery()->from($this->from);
  1468. }
  1469. /**
  1470. * Add another query builder as a nested where to the query builder.
  1471. *
  1472. * @param \Illuminate\Database\Query\Builder $query
  1473. * @param string $boolean
  1474. * @return $this
  1475. */
  1476. public function addNestedWhereQuery($query, $boolean = 'and')
  1477. {
  1478. if (count($query->wheres)) {
  1479. $type = 'Nested';
  1480. $this->wheres[] = compact('type', 'query', 'boolean');
  1481. $this->addBinding($query->getRawBindings()['where'], 'where');
  1482. }
  1483. return $this;
  1484. }
  1485. /**
  1486. * Add a full sub-select to the query.
  1487. *
  1488. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  1489. * @param string $operator
  1490. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $callback
  1491. * @param string $boolean
  1492. * @return $this
  1493. */
  1494. protected function whereSub($column, $operator, $callback, $boolean)
  1495. {
  1496. $type = 'Sub';
  1497. if ($callback instanceof Closure) {
  1498. // Once we have the query instance we can simply execute it so it can add all
  1499. // of the sub-select's conditions to itself, and then we can cache it off
  1500. // in the array of where clauses for the "main" parent query instance.
  1501. $callback($query = $this->forSubQuery());
  1502. } else {
  1503. $query = $callback instanceof EloquentBuilder ? $callback->toBase() : $callback;
  1504. }
  1505. $this->wheres[] = compact(
  1506. 'type', 'column', 'operator', 'query', 'boolean'
  1507. );
  1508. $this->addBinding($query->getBindings(), 'where');
  1509. return $this;
  1510. }
  1511. /**
  1512. * Add an exists clause to the query.
  1513. *
  1514. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $callback
  1515. * @param string $boolean
  1516. * @param bool $not
  1517. * @return $this
  1518. */
  1519. public function whereExists($callback, $boolean = 'and', $not = false)
  1520. {
  1521. if ($callback instanceof Closure) {
  1522. $query = $this->forSubQuery();
  1523. // Similar to the sub-select clause, we will create a new query instance so
  1524. // the developer may cleanly specify the entire exists query and we will
  1525. // compile the whole thing in the grammar and insert it into the SQL.
  1526. $callback($query);
  1527. } else {
  1528. $query = $callback instanceof EloquentBuilder ? $callback->toBase() : $callback;
  1529. }
  1530. return $this->addWhereExistsQuery($query, $boolean, $not);
  1531. }
  1532. /**
  1533. * Add an or exists clause to the query.
  1534. *
  1535. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $callback
  1536. * @param bool $not
  1537. * @return $this
  1538. */
  1539. public function orWhereExists($callback, $not = false)
  1540. {
  1541. return $this->whereExists($callback, 'or', $not);
  1542. }
  1543. /**
  1544. * Add a where not exists clause to the query.
  1545. *
  1546. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $callback
  1547. * @param string $boolean
  1548. * @return $this
  1549. */
  1550. public function whereNotExists($callback, $boolean = 'and')
  1551. {
  1552. return $this->whereExists($callback, $boolean, true);
  1553. }
  1554. /**
  1555. * Add a where not exists clause to the query.
  1556. *
  1557. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $callback
  1558. * @return $this
  1559. */
  1560. public function orWhereNotExists($callback)
  1561. {
  1562. return $this->orWhereExists($callback, true);
  1563. }
  1564. /**
  1565. * Add an exists clause to the query.
  1566. *
  1567. * @param \Illuminate\Database\Query\Builder $query
  1568. * @param string $boolean
  1569. * @param bool $not
  1570. * @return $this
  1571. */
  1572. public function addWhereExistsQuery(self $query, $boolean = 'and', $not = false)
  1573. {
  1574. $type = $not ? 'NotExists' : 'Exists';
  1575. $this->wheres[] = compact('type', 'query', 'boolean');
  1576. $this->addBinding($query->getBindings(), 'where');
  1577. return $this;
  1578. }
  1579. /**
  1580. * Adds a where condition using row values.
  1581. *
  1582. * @param array $columns
  1583. * @param string $operator
  1584. * @param array $values
  1585. * @param string $boolean
  1586. * @return $this
  1587. *
  1588. * @throws \InvalidArgumentException
  1589. */
  1590. public function whereRowValues($columns, $operator, $values, $boolean = 'and')
  1591. {
  1592. if (count($columns) !== count($values)) {
  1593. throw new InvalidArgumentException('The number of columns must match the number of values');
  1594. }
  1595. $type = 'RowValues';
  1596. $this->wheres[] = compact('type', 'columns', 'operator', 'values', 'boolean');
  1597. $this->addBinding($this->cleanBindings($values));
  1598. return $this;
  1599. }
  1600. /**
  1601. * Adds an or where condition using row values.
  1602. *
  1603. * @param array $columns
  1604. * @param string $operator
  1605. * @param array $values
  1606. * @return $this
  1607. */
  1608. public function orWhereRowValues($columns, $operator, $values)
  1609. {
  1610. return $this->whereRowValues($columns, $operator, $values, 'or');
  1611. }
  1612. /**
  1613. * Add a "where JSON contains" clause to the query.
  1614. *
  1615. * @param string $column
  1616. * @param mixed $value
  1617. * @param string $boolean
  1618. * @param bool $not
  1619. * @return $this
  1620. */
  1621. public function whereJsonContains($column, $value, $boolean = 'and', $not = false)
  1622. {
  1623. $type = 'JsonContains';
  1624. $this->wheres[] = compact('type', 'column', 'value', 'boolean', 'not');
  1625. if (! $value instanceof ExpressionContract) {
  1626. $this->addBinding($this->grammar->prepareBindingForJsonContains($value));
  1627. }
  1628. return $this;
  1629. }
  1630. /**
  1631. * Add an "or where JSON contains" clause to the query.
  1632. *
  1633. * @param string $column
  1634. * @param mixed $value
  1635. * @return $this
  1636. */
  1637. public function orWhereJsonContains($column, $value)
  1638. {
  1639. return $this->whereJsonContains($column, $value, 'or');
  1640. }
  1641. /**
  1642. * Add a "where JSON not contains" clause to the query.
  1643. *
  1644. * @param string $column
  1645. * @param mixed $value
  1646. * @param string $boolean
  1647. * @return $this
  1648. */
  1649. public function whereJsonDoesntContain($column, $value, $boolean = 'and')
  1650. {
  1651. return $this->whereJsonContains($column, $value, $boolean, true);
  1652. }
  1653. /**
  1654. * Add an "or where JSON not contains" clause to the query.
  1655. *
  1656. * @param string $column
  1657. * @param mixed $value
  1658. * @return $this
  1659. */
  1660. public function orWhereJsonDoesntContain($column, $value)
  1661. {
  1662. return $this->whereJsonDoesntContain($column, $value, 'or');
  1663. }
  1664. /**
  1665. * Add a "where JSON overlaps" clause to the query.
  1666. *
  1667. * @param string $column
  1668. * @param mixed $value
  1669. * @param string $boolean
  1670. * @param bool $not
  1671. * @return $this
  1672. */
  1673. public function whereJsonOverlaps($column, $value, $boolean = 'and', $not = false)
  1674. {
  1675. $type = 'JsonOverlaps';
  1676. $this->wheres[] = compact('type', 'column', 'value', 'boolean', 'not');
  1677. if (! $value instanceof ExpressionContract) {
  1678. $this->addBinding($this->grammar->prepareBindingForJsonContains($value));
  1679. }
  1680. return $this;
  1681. }
  1682. /**
  1683. * Add an "or where JSON overlaps" clause to the query.
  1684. *
  1685. * @param string $column
  1686. * @param mixed $value
  1687. * @return $this
  1688. */
  1689. public function orWhereJsonOverlaps($column, $value)
  1690. {
  1691. return $this->whereJsonOverlaps($column, $value, 'or');
  1692. }
  1693. /**
  1694. * Add a "where JSON not overlap" clause to the query.
  1695. *
  1696. * @param string $column
  1697. * @param mixed $value
  1698. * @param string $boolean
  1699. * @return $this
  1700. */
  1701. public function whereJsonDoesntOverlap($column, $value, $boolean = 'and')
  1702. {
  1703. return $this->whereJsonOverlaps($column, $value, $boolean, true);
  1704. }
  1705. /**
  1706. * Add an "or where JSON not overlap" clause to the query.
  1707. *
  1708. * @param string $column
  1709. * @param mixed $value
  1710. * @return $this
  1711. */
  1712. public function orWhereJsonDoesntOverlap($column, $value)
  1713. {
  1714. return $this->whereJsonDoesntOverlap($column, $value, 'or');
  1715. }
  1716. /**
  1717. * Add a clause that determines if a JSON path exists to the query.
  1718. *
  1719. * @param string $column
  1720. * @param string $boolean
  1721. * @param bool $not
  1722. * @return $this
  1723. */
  1724. public function whereJsonContainsKey($column, $boolean = 'and', $not = false)
  1725. {
  1726. $type = 'JsonContainsKey';
  1727. $this->wheres[] = compact('type', 'column', 'boolean', 'not');
  1728. return $this;
  1729. }
  1730. /**
  1731. * Add an "or" clause that determines if a JSON path exists to the query.
  1732. *
  1733. * @param string $column
  1734. * @return $this
  1735. */
  1736. public function orWhereJsonContainsKey($column)
  1737. {
  1738. return $this->whereJsonContainsKey($column, 'or');
  1739. }
  1740. /**
  1741. * Add a clause that determines if a JSON path does not exist to the query.
  1742. *
  1743. * @param string $column
  1744. * @param string $boolean
  1745. * @return $this
  1746. */
  1747. public function whereJsonDoesntContainKey($column, $boolean = 'and')
  1748. {
  1749. return $this->whereJsonContainsKey($column, $boolean, true);
  1750. }
  1751. /**
  1752. * Add an "or" clause that determines if a JSON path does not exist to the query.
  1753. *
  1754. * @param string $column
  1755. * @return $this
  1756. */
  1757. public function orWhereJsonDoesntContainKey($column)
  1758. {
  1759. return $this->whereJsonDoesntContainKey($column, 'or');
  1760. }
  1761. /**
  1762. * Add a "where JSON length" clause to the query.
  1763. *
  1764. * @param string $column
  1765. * @param mixed $operator
  1766. * @param mixed $value
  1767. * @param string $boolean
  1768. * @return $this
  1769. */
  1770. public function whereJsonLength($column, $operator, $value = null, $boolean = 'and')
  1771. {
  1772. $type = 'JsonLength';
  1773. [$value, $operator] = $this->prepareValueAndOperator(
  1774. $value, $operator, func_num_args() === 2
  1775. );
  1776. $this->wheres[] = compact('type', 'column', 'operator', 'value', 'boolean');
  1777. if (! $value instanceof ExpressionContract) {
  1778. $this->addBinding((int) $this->flattenValue($value));
  1779. }
  1780. return $this;
  1781. }
  1782. /**
  1783. * Add an "or where JSON length" clause to the query.
  1784. *
  1785. * @param string $column
  1786. * @param mixed $operator
  1787. * @param mixed $value
  1788. * @return $this
  1789. */
  1790. public function orWhereJsonLength($column, $operator, $value = null)
  1791. {
  1792. [$value, $operator] = $this->prepareValueAndOperator(
  1793. $value, $operator, func_num_args() === 2
  1794. );
  1795. return $this->whereJsonLength($column, $operator, $value, 'or');
  1796. }
  1797. /**
  1798. * Handles dynamic "where" clauses to the query.
  1799. *
  1800. * @param string $method
  1801. * @param array $parameters
  1802. * @return $this
  1803. */
  1804. public function dynamicWhere($method, $parameters)
  1805. {
  1806. $finder = substr($method, 5);
  1807. $segments = preg_split(
  1808. '/(And|Or)(?=[A-Z])/', $finder, -1, PREG_SPLIT_DELIM_CAPTURE
  1809. );
  1810. // The connector variable will determine which connector will be used for the
  1811. // query condition. We will change it as we come across new boolean values
  1812. // in the dynamic method strings, which could contain a number of these.
  1813. $connector = 'and';
  1814. $index = 0;
  1815. foreach ($segments as $segment) {
  1816. // If the segment is not a boolean connector, we can assume it is a column's name
  1817. // and we will add it to the query as a new constraint as a where clause, then
  1818. // we can keep iterating through the dynamic method string's segments again.
  1819. if ($segment !== 'And' && $segment !== 'Or') {
  1820. $this->addDynamic($segment, $connector, $parameters, $index);
  1821. $index++;
  1822. }
  1823. // Otherwise, we will store the connector so we know how the next where clause we
  1824. // find in the query should be connected to the previous ones, meaning we will
  1825. // have the proper boolean connector to connect the next where clause found.
  1826. else {
  1827. $connector = $segment;
  1828. }
  1829. }
  1830. return $this;
  1831. }
  1832. /**
  1833. * Add a single dynamic where clause statement to the query.
  1834. *
  1835. * @param string $segment
  1836. * @param string $connector
  1837. * @param array $parameters
  1838. * @param int $index
  1839. * @return void
  1840. */
  1841. protected function addDynamic($segment, $connector, $parameters, $index)
  1842. {
  1843. // Once we have parsed out the columns and formatted the boolean operators we
  1844. // are ready to add it to this query as a where clause just like any other
  1845. // clause on the query. Then we'll increment the parameter index values.
  1846. $bool = strtolower($connector);
  1847. $this->where(Str::snake($segment), '=', $parameters[$index], $bool);
  1848. }
  1849. /**
  1850. * Add a "where fulltext" clause to the query.
  1851. *
  1852. * @param string|string[] $columns
  1853. * @param string $value
  1854. * @param string $boolean
  1855. * @return $this
  1856. */
  1857. public function whereFullText($columns, $value, array $options = [], $boolean = 'and')
  1858. {
  1859. $type = 'Fulltext';
  1860. $columns = (array) $columns;
  1861. $this->wheres[] = compact('type', 'columns', 'value', 'options', 'boolean');
  1862. $this->addBinding($value);
  1863. return $this;
  1864. }
  1865. /**
  1866. * Add a "or where fulltext" clause to the query.
  1867. *
  1868. * @param string|string[] $columns
  1869. * @param string $value
  1870. * @return $this
  1871. */
  1872. public function orWhereFullText($columns, $value, array $options = [])
  1873. {
  1874. return $this->whereFulltext($columns, $value, $options, 'or');
  1875. }
  1876. /**
  1877. * Add a "where" clause to the query for multiple columns with "and" conditions between them.
  1878. *
  1879. * @param string[] $columns
  1880. * @param mixed $operator
  1881. * @param mixed $value
  1882. * @param string $boolean
  1883. * @return $this
  1884. */
  1885. public function whereAll($columns, $operator = null, $value = null, $boolean = 'and')
  1886. {
  1887. [$value, $operator] = $this->prepareValueAndOperator(
  1888. $value, $operator, func_num_args() === 2
  1889. );
  1890. $this->whereNested(function ($query) use ($columns, $operator, $value) {
  1891. foreach ($columns as $column) {
  1892. $query->where($column, $operator, $value, 'and');
  1893. }
  1894. }, $boolean);
  1895. return $this;
  1896. }
  1897. /**
  1898. * Add an "or where" clause to the query for multiple columns with "and" conditions between them.
  1899. *
  1900. * @param string[] $columns
  1901. * @param string $operator
  1902. * @param mixed $value
  1903. * @return $this
  1904. */
  1905. public function orWhereAll($columns, $operator = null, $value = null)
  1906. {
  1907. return $this->whereAll($columns, $operator, $value, 'or');
  1908. }
  1909. /**
  1910. * Add an "where" clause to the query for multiple columns with "or" conditions between them.
  1911. *
  1912. * @param string[] $columns
  1913. * @param string $operator
  1914. * @param mixed $value
  1915. * @param string $boolean
  1916. * @return $this
  1917. */
  1918. public function whereAny($columns, $operator = null, $value = null, $boolean = 'and')
  1919. {
  1920. [$value, $operator] = $this->prepareValueAndOperator(
  1921. $value, $operator, func_num_args() === 2
  1922. );
  1923. $this->whereNested(function ($query) use ($columns, $operator, $value) {
  1924. foreach ($columns as $column) {
  1925. $query->where($column, $operator, $value, 'or');
  1926. }
  1927. }, $boolean);
  1928. return $this;
  1929. }
  1930. /**
  1931. * Add an "or where" clause to the query for multiple columns with "or" conditions between them.
  1932. *
  1933. * @param string[] $columns
  1934. * @param string $operator
  1935. * @param mixed $value
  1936. * @return $this
  1937. */
  1938. public function orWhereAny($columns, $operator = null, $value = null)
  1939. {
  1940. return $this->whereAny($columns, $operator, $value, 'or');
  1941. }
  1942. /**
  1943. * Add a "group by" clause to the query.
  1944. *
  1945. * @param array|\Illuminate\Contracts\Database\Query\Expression|string ...$groups
  1946. * @return $this
  1947. */
  1948. public function groupBy(...$groups)
  1949. {
  1950. foreach ($groups as $group) {
  1951. $this->groups = array_merge(
  1952. (array) $this->groups,
  1953. Arr::wrap($group)
  1954. );
  1955. }
  1956. return $this;
  1957. }
  1958. /**
  1959. * Add a raw groupBy clause to the query.
  1960. *
  1961. * @param string $sql
  1962. * @param array $bindings
  1963. * @return $this
  1964. */
  1965. public function groupByRaw($sql, array $bindings = [])
  1966. {
  1967. $this->groups[] = new Expression($sql);
  1968. $this->addBinding($bindings, 'groupBy');
  1969. return $this;
  1970. }
  1971. /**
  1972. * Add a "having" clause to the query.
  1973. *
  1974. * @param \Illuminate\Contracts\Database\Query\Expression|\Closure|string $column
  1975. * @param string|int|float|null $operator
  1976. * @param string|int|float|null $value
  1977. * @param string $boolean
  1978. * @return $this
  1979. */
  1980. public function having($column, $operator = null, $value = null, $boolean = 'and')
  1981. {
  1982. $type = 'Basic';
  1983. if ($column instanceof ConditionExpression) {
  1984. $type = 'Expression';
  1985. $this->havings[] = compact('type', 'column', 'boolean');
  1986. return $this;
  1987. }
  1988. // Here we will make some assumptions about the operator. If only 2 values are
  1989. // passed to the method, we will assume that the operator is an equals sign
  1990. // and keep going. Otherwise, we'll require the operator to be passed in.
  1991. [$value, $operator] = $this->prepareValueAndOperator(
  1992. $value, $operator, func_num_args() === 2
  1993. );
  1994. if ($column instanceof Closure && is_null($operator)) {
  1995. return $this->havingNested($column, $boolean);
  1996. }
  1997. // If the given operator is not found in the list of valid operators we will
  1998. // assume that the developer is just short-cutting the '=' operators and
  1999. // we will set the operators to '=' and set the values appropriately.
  2000. if ($this->invalidOperator($operator)) {
  2001. [$value, $operator] = [$operator, '='];
  2002. }
  2003. if ($this->isBitwiseOperator($operator)) {
  2004. $type = 'Bitwise';
  2005. }
  2006. $this->havings[] = compact('type', 'column', 'operator', 'value', 'boolean');
  2007. if (! $value instanceof ExpressionContract) {
  2008. $this->addBinding($this->flattenValue($value), 'having');
  2009. }
  2010. return $this;
  2011. }
  2012. /**
  2013. * Add an "or having" clause to the query.
  2014. *
  2015. * @param \Illuminate\Contracts\Database\Query\Expression|\Closure|string $column
  2016. * @param string|int|float|null $operator
  2017. * @param string|int|float|null $value
  2018. * @return $this
  2019. */
  2020. public function orHaving($column, $operator = null, $value = null)
  2021. {
  2022. [$value, $operator] = $this->prepareValueAndOperator(
  2023. $value, $operator, func_num_args() === 2
  2024. );
  2025. return $this->having($column, $operator, $value, 'or');
  2026. }
  2027. /**
  2028. * Add a nested having statement to the query.
  2029. *
  2030. * @param \Closure $callback
  2031. * @param string $boolean
  2032. * @return $this
  2033. */
  2034. public function havingNested(Closure $callback, $boolean = 'and')
  2035. {
  2036. $callback($query = $this->forNestedWhere());
  2037. return $this->addNestedHavingQuery($query, $boolean);
  2038. }
  2039. /**
  2040. * Add another query builder as a nested having to the query builder.
  2041. *
  2042. * @param \Illuminate\Database\Query\Builder $query
  2043. * @param string $boolean
  2044. * @return $this
  2045. */
  2046. public function addNestedHavingQuery($query, $boolean = 'and')
  2047. {
  2048. if (count($query->havings)) {
  2049. $type = 'Nested';
  2050. $this->havings[] = compact('type', 'query', 'boolean');
  2051. $this->addBinding($query->getRawBindings()['having'], 'having');
  2052. }
  2053. return $this;
  2054. }
  2055. /**
  2056. * Add a "having null" clause to the query.
  2057. *
  2058. * @param string|array $columns
  2059. * @param string $boolean
  2060. * @param bool $not
  2061. * @return $this
  2062. */
  2063. public function havingNull($columns, $boolean = 'and', $not = false)
  2064. {
  2065. $type = $not ? 'NotNull' : 'Null';
  2066. foreach (Arr::wrap($columns) as $column) {
  2067. $this->havings[] = compact('type', 'column', 'boolean');
  2068. }
  2069. return $this;
  2070. }
  2071. /**
  2072. * Add an "or having null" clause to the query.
  2073. *
  2074. * @param string $column
  2075. * @return $this
  2076. */
  2077. public function orHavingNull($column)
  2078. {
  2079. return $this->havingNull($column, 'or');
  2080. }
  2081. /**
  2082. * Add a "having not null" clause to the query.
  2083. *
  2084. * @param string|array $columns
  2085. * @param string $boolean
  2086. * @return $this
  2087. */
  2088. public function havingNotNull($columns, $boolean = 'and')
  2089. {
  2090. return $this->havingNull($columns, $boolean, true);
  2091. }
  2092. /**
  2093. * Add an "or having not null" clause to the query.
  2094. *
  2095. * @param string $column
  2096. * @return $this
  2097. */
  2098. public function orHavingNotNull($column)
  2099. {
  2100. return $this->havingNotNull($column, 'or');
  2101. }
  2102. /**
  2103. * Add a "having between " clause to the query.
  2104. *
  2105. * @param string $column
  2106. * @param iterable $values
  2107. * @param string $boolean
  2108. * @param bool $not
  2109. * @return $this
  2110. */
  2111. public function havingBetween($column, iterable $values, $boolean = 'and', $not = false)
  2112. {
  2113. $type = 'between';
  2114. if ($values instanceof CarbonPeriod) {
  2115. $values = [$values->getStartDate(), $values->getEndDate()];
  2116. }
  2117. $this->havings[] = compact('type', 'column', 'values', 'boolean', 'not');
  2118. $this->addBinding(array_slice($this->cleanBindings(Arr::flatten($values)), 0, 2), 'having');
  2119. return $this;
  2120. }
  2121. /**
  2122. * Add a raw having clause to the query.
  2123. *
  2124. * @param string $sql
  2125. * @param array $bindings
  2126. * @param string $boolean
  2127. * @return $this
  2128. */
  2129. public function havingRaw($sql, array $bindings = [], $boolean = 'and')
  2130. {
  2131. $type = 'Raw';
  2132. $this->havings[] = compact('type', 'sql', 'boolean');
  2133. $this->addBinding($bindings, 'having');
  2134. return $this;
  2135. }
  2136. /**
  2137. * Add a raw or having clause to the query.
  2138. *
  2139. * @param string $sql
  2140. * @param array $bindings
  2141. * @return $this
  2142. */
  2143. public function orHavingRaw($sql, array $bindings = [])
  2144. {
  2145. return $this->havingRaw($sql, $bindings, 'or');
  2146. }
  2147. /**
  2148. * Add an "order by" clause to the query.
  2149. *
  2150. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Contracts\Database\Query\Expression|string $column
  2151. * @param string $direction
  2152. * @return $this
  2153. *
  2154. * @throws \InvalidArgumentException
  2155. */
  2156. public function orderBy($column, $direction = 'asc')
  2157. {
  2158. if ($this->isQueryable($column)) {
  2159. [$query, $bindings] = $this->createSub($column);
  2160. $column = new Expression('('.$query.')');
  2161. $this->addBinding($bindings, $this->unions ? 'unionOrder' : 'order');
  2162. }
  2163. $direction = strtolower($direction);
  2164. if (! in_array($direction, ['asc', 'desc'], true)) {
  2165. throw new InvalidArgumentException('Order direction must be "asc" or "desc".');
  2166. }
  2167. $this->{$this->unions ? 'unionOrders' : 'orders'}[] = [
  2168. 'column' => $column,
  2169. 'direction' => $direction,
  2170. ];
  2171. return $this;
  2172. }
  2173. /**
  2174. * Add a descending "order by" clause to the query.
  2175. *
  2176. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|\Illuminate\Contracts\Database\Query\Expression|string $column
  2177. * @return $this
  2178. */
  2179. public function orderByDesc($column)
  2180. {
  2181. return $this->orderBy($column, 'desc');
  2182. }
  2183. /**
  2184. * Add an "order by" clause for a timestamp to the query.
  2185. *
  2186. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Contracts\Database\Query\Expression|string $column
  2187. * @return $this
  2188. */
  2189. public function latest($column = 'created_at')
  2190. {
  2191. return $this->orderBy($column, 'desc');
  2192. }
  2193. /**
  2194. * Add an "order by" clause for a timestamp to the query.
  2195. *
  2196. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Contracts\Database\Query\Expression|string $column
  2197. * @return $this
  2198. */
  2199. public function oldest($column = 'created_at')
  2200. {
  2201. return $this->orderBy($column, 'asc');
  2202. }
  2203. /**
  2204. * Put the query's results in random order.
  2205. *
  2206. * @param string|int $seed
  2207. * @return $this
  2208. */
  2209. public function inRandomOrder($seed = '')
  2210. {
  2211. return $this->orderByRaw($this->grammar->compileRandom($seed));
  2212. }
  2213. /**
  2214. * Add a raw "order by" clause to the query.
  2215. *
  2216. * @param string $sql
  2217. * @param array $bindings
  2218. * @return $this
  2219. */
  2220. public function orderByRaw($sql, $bindings = [])
  2221. {
  2222. $type = 'Raw';
  2223. $this->{$this->unions ? 'unionOrders' : 'orders'}[] = compact('type', 'sql');
  2224. $this->addBinding($bindings, $this->unions ? 'unionOrder' : 'order');
  2225. return $this;
  2226. }
  2227. /**
  2228. * Alias to set the "offset" value of the query.
  2229. *
  2230. * @param int $value
  2231. * @return $this
  2232. */
  2233. public function skip($value)
  2234. {
  2235. return $this->offset($value);
  2236. }
  2237. /**
  2238. * Set the "offset" value of the query.
  2239. *
  2240. * @param int $value
  2241. * @return $this
  2242. */
  2243. public function offset($value)
  2244. {
  2245. $property = $this->unions ? 'unionOffset' : 'offset';
  2246. $this->$property = max(0, (int) $value);
  2247. return $this;
  2248. }
  2249. /**
  2250. * Alias to set the "limit" value of the query.
  2251. *
  2252. * @param int $value
  2253. * @return $this
  2254. */
  2255. public function take($value)
  2256. {
  2257. return $this->limit($value);
  2258. }
  2259. /**
  2260. * Set the "limit" value of the query.
  2261. *
  2262. * @param int $value
  2263. * @return $this
  2264. */
  2265. public function limit($value)
  2266. {
  2267. $property = $this->unions ? 'unionLimit' : 'limit';
  2268. if ($value >= 0) {
  2269. $this->$property = ! is_null($value) ? (int) $value : null;
  2270. }
  2271. return $this;
  2272. }
  2273. /**
  2274. * Add a "group limit" clause to the query.
  2275. *
  2276. * @param int $value
  2277. * @param string $column
  2278. * @return $this
  2279. */
  2280. public function groupLimit($value, $column)
  2281. {
  2282. if ($value >= 0) {
  2283. $this->groupLimit = compact('value', 'column');
  2284. }
  2285. return $this;
  2286. }
  2287. /**
  2288. * Set the limit and offset for a given page.
  2289. *
  2290. * @param int $page
  2291. * @param int $perPage
  2292. * @return $this
  2293. */
  2294. public function forPage($page, $perPage = 15)
  2295. {
  2296. return $this->offset(($page - 1) * $perPage)->limit($perPage);
  2297. }
  2298. /**
  2299. * Constrain the query to the previous "page" of results before a given ID.
  2300. *
  2301. * @param int $perPage
  2302. * @param int|null $lastId
  2303. * @param string $column
  2304. * @return $this
  2305. */
  2306. public function forPageBeforeId($perPage = 15, $lastId = 0, $column = 'id')
  2307. {
  2308. $this->orders = $this->removeExistingOrdersFor($column);
  2309. if (! is_null($lastId)) {
  2310. $this->where($column, '<', $lastId);
  2311. }
  2312. return $this->orderBy($column, 'desc')
  2313. ->limit($perPage);
  2314. }
  2315. /**
  2316. * Constrain the query to the next "page" of results after a given ID.
  2317. *
  2318. * @param int $perPage
  2319. * @param int|null $lastId
  2320. * @param string $column
  2321. * @return $this
  2322. */
  2323. public function forPageAfterId($perPage = 15, $lastId = 0, $column = 'id')
  2324. {
  2325. $this->orders = $this->removeExistingOrdersFor($column);
  2326. if (! is_null($lastId)) {
  2327. $this->where($column, '>', $lastId);
  2328. }
  2329. return $this->orderBy($column, 'asc')
  2330. ->limit($perPage);
  2331. }
  2332. /**
  2333. * Remove all existing orders and optionally add a new order.
  2334. *
  2335. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Contracts\Database\Query\Expression|string|null $column
  2336. * @param string $direction
  2337. * @return $this
  2338. */
  2339. public function reorder($column = null, $direction = 'asc')
  2340. {
  2341. $this->orders = null;
  2342. $this->unionOrders = null;
  2343. $this->bindings['order'] = [];
  2344. $this->bindings['unionOrder'] = [];
  2345. if ($column) {
  2346. return $this->orderBy($column, $direction);
  2347. }
  2348. return $this;
  2349. }
  2350. /**
  2351. * Get an array with all orders with a given column removed.
  2352. *
  2353. * @param string $column
  2354. * @return array
  2355. */
  2356. protected function removeExistingOrdersFor($column)
  2357. {
  2358. return Collection::make($this->orders)
  2359. ->reject(function ($order) use ($column) {
  2360. return isset($order['column'])
  2361. ? $order['column'] === $column : false;
  2362. })->values()->all();
  2363. }
  2364. /**
  2365. * Add a union statement to the query.
  2366. *
  2367. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $query
  2368. * @param bool $all
  2369. * @return $this
  2370. */
  2371. public function union($query, $all = false)
  2372. {
  2373. if ($query instanceof Closure) {
  2374. $query($query = $this->newQuery());
  2375. }
  2376. $this->unions[] = compact('query', 'all');
  2377. $this->addBinding($query->getBindings(), 'union');
  2378. return $this;
  2379. }
  2380. /**
  2381. * Add a union all statement to the query.
  2382. *
  2383. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder $query
  2384. * @return $this
  2385. */
  2386. public function unionAll($query)
  2387. {
  2388. return $this->union($query, true);
  2389. }
  2390. /**
  2391. * Lock the selected rows in the table.
  2392. *
  2393. * @param string|bool $value
  2394. * @return $this
  2395. */
  2396. public function lock($value = true)
  2397. {
  2398. $this->lock = $value;
  2399. if (! is_null($this->lock)) {
  2400. $this->useWritePdo();
  2401. }
  2402. return $this;
  2403. }
  2404. /**
  2405. * Lock the selected rows in the table for updating.
  2406. *
  2407. * @return $this
  2408. */
  2409. public function lockForUpdate()
  2410. {
  2411. return $this->lock(true);
  2412. }
  2413. /**
  2414. * Share lock the selected rows in the table.
  2415. *
  2416. * @return $this
  2417. */
  2418. public function sharedLock()
  2419. {
  2420. return $this->lock(false);
  2421. }
  2422. /**
  2423. * Register a closure to be invoked before the query is executed.
  2424. *
  2425. * @param callable $callback
  2426. * @return $this
  2427. */
  2428. public function beforeQuery(callable $callback)
  2429. {
  2430. $this->beforeQueryCallbacks[] = $callback;
  2431. return $this;
  2432. }
  2433. /**
  2434. * Invoke the "before query" modification callbacks.
  2435. *
  2436. * @return void
  2437. */
  2438. public function applyBeforeQueryCallbacks()
  2439. {
  2440. foreach ($this->beforeQueryCallbacks as $callback) {
  2441. $callback($this);
  2442. }
  2443. $this->beforeQueryCallbacks = [];
  2444. }
  2445. /**
  2446. * Register a closure to be invoked after the query is executed.
  2447. *
  2448. * @param \Closure $callback
  2449. * @return $this
  2450. */
  2451. public function afterQuery(Closure $callback)
  2452. {
  2453. $this->afterQueryCallbacks[] = $callback;
  2454. return $this;
  2455. }
  2456. /**
  2457. * Invoke the "after query" modification callbacks.
  2458. *
  2459. * @param mixed $result
  2460. * @return mixed
  2461. */
  2462. public function applyAfterQueryCallbacks($result)
  2463. {
  2464. foreach ($this->afterQueryCallbacks as $afterQueryCallback) {
  2465. $result = $afterQueryCallback($result) ?: $result;
  2466. }
  2467. return $result;
  2468. }
  2469. /**
  2470. * Get the SQL representation of the query.
  2471. *
  2472. * @return string
  2473. */
  2474. public function toSql()
  2475. {
  2476. $this->applyBeforeQueryCallbacks();
  2477. return $this->grammar->compileSelect($this);
  2478. }
  2479. /**
  2480. * Get the raw SQL representation of the query with embedded bindings.
  2481. *
  2482. * @return string
  2483. */
  2484. public function toRawSql()
  2485. {
  2486. return $this->grammar->substituteBindingsIntoRawSql(
  2487. $this->toSql(), $this->connection->prepareBindings($this->getBindings())
  2488. );
  2489. }
  2490. /**
  2491. * Execute a query for a single record by ID.
  2492. *
  2493. * @param int|string $id
  2494. * @param array|string $columns
  2495. * @return mixed|static
  2496. */
  2497. public function find($id, $columns = ['*'])
  2498. {
  2499. return $this->where('id', '=', $id)->first($columns);
  2500. }
  2501. /**
  2502. * Execute a query for a single record by ID or call a callback.
  2503. *
  2504. * @param mixed $id
  2505. * @param \Closure|array|string $columns
  2506. * @param \Closure|null $callback
  2507. * @return mixed|static
  2508. */
  2509. public function findOr($id, $columns = ['*'], ?Closure $callback = null)
  2510. {
  2511. if ($columns instanceof Closure) {
  2512. $callback = $columns;
  2513. $columns = ['*'];
  2514. }
  2515. if (! is_null($data = $this->find($id, $columns))) {
  2516. return $data;
  2517. }
  2518. return $callback();
  2519. }
  2520. /**
  2521. * Get a single column's value from the first result of a query.
  2522. *
  2523. * @param string $column
  2524. * @return mixed
  2525. */
  2526. public function value($column)
  2527. {
  2528. $result = (array) $this->first([$column]);
  2529. return count($result) > 0 ? reset($result) : null;
  2530. }
  2531. /**
  2532. * Get a single expression value from the first result of a query.
  2533. *
  2534. * @param string $expression
  2535. * @param array $bindings
  2536. * @return mixed
  2537. */
  2538. public function rawValue(string $expression, array $bindings = [])
  2539. {
  2540. $result = (array) $this->selectRaw($expression, $bindings)->first();
  2541. return count($result) > 0 ? reset($result) : null;
  2542. }
  2543. /**
  2544. * Get a single column's value from the first result of a query if it's the sole matching record.
  2545. *
  2546. * @param string $column
  2547. * @return mixed
  2548. *
  2549. * @throws \Illuminate\Database\RecordsNotFoundException
  2550. * @throws \Illuminate\Database\MultipleRecordsFoundException
  2551. */
  2552. public function soleValue($column)
  2553. {
  2554. $result = (array) $this->sole([$column]);
  2555. return reset($result);
  2556. }
  2557. /**
  2558. * Execute the query as a "select" statement.
  2559. *
  2560. * @param array|string $columns
  2561. * @return \Illuminate\Support\Collection
  2562. */
  2563. public function get($columns = ['*'])
  2564. {
  2565. $items = collect($this->onceWithColumns(Arr::wrap($columns), function () {
  2566. return $this->processor->processSelect($this, $this->runSelect());
  2567. }));
  2568. return $this->applyAfterQueryCallbacks(
  2569. isset($this->groupLimit) ? $this->withoutGroupLimitKeys($items) : $items
  2570. );
  2571. }
  2572. /**
  2573. * Run the query as a "select" statement against the connection.
  2574. *
  2575. * @return array
  2576. */
  2577. protected function runSelect()
  2578. {
  2579. return $this->connection->select(
  2580. $this->toSql(), $this->getBindings(), ! $this->useWritePdo
  2581. );
  2582. }
  2583. /**
  2584. * Remove the group limit keys from the results in the collection.
  2585. *
  2586. * @param \Illuminate\Support\Collection $items
  2587. * @return \Illuminate\Support\Collection
  2588. */
  2589. protected function withoutGroupLimitKeys($items)
  2590. {
  2591. $keysToRemove = ['laravel_row'];
  2592. if (is_string($this->groupLimit['column'])) {
  2593. $column = last(explode('.', $this->groupLimit['column']));
  2594. $keysToRemove[] = '@laravel_group := '.$this->grammar->wrap($column);
  2595. $keysToRemove[] = '@laravel_group := '.$this->grammar->wrap('pivot_'.$column);
  2596. }
  2597. $items->each(function ($item) use ($keysToRemove) {
  2598. foreach ($keysToRemove as $key) {
  2599. unset($item->$key);
  2600. }
  2601. });
  2602. return $items;
  2603. }
  2604. /**
  2605. * Paginate the given query into a simple paginator.
  2606. *
  2607. * @param int|\Closure $perPage
  2608. * @param array|string $columns
  2609. * @param string $pageName
  2610. * @param int|null $page
  2611. * @param \Closure|int|null $total
  2612. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2613. */
  2614. public function paginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null, $total = null)
  2615. {
  2616. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  2617. $total = value($total) ?? $this->getCountForPagination();
  2618. $perPage = $perPage instanceof Closure ? $perPage($total) : $perPage;
  2619. $results = $total ? $this->forPage($page, $perPage)->get($columns) : collect();
  2620. return $this->paginator($results, $total, $perPage, $page, [
  2621. 'path' => Paginator::resolveCurrentPath(),
  2622. 'pageName' => $pageName,
  2623. ]);
  2624. }
  2625. /**
  2626. * Get a paginator only supporting simple next and previous links.
  2627. *
  2628. * This is more efficient on larger data-sets, etc.
  2629. *
  2630. * @param int $perPage
  2631. * @param array|string $columns
  2632. * @param string $pageName
  2633. * @param int|null $page
  2634. * @return \Illuminate\Contracts\Pagination\Paginator
  2635. */
  2636. public function simplePaginate($perPage = 15, $columns = ['*'], $pageName = 'page', $page = null)
  2637. {
  2638. $page = $page ?: Paginator::resolveCurrentPage($pageName);
  2639. $this->offset(($page - 1) * $perPage)->limit($perPage + 1);
  2640. return $this->simplePaginator($this->get($columns), $perPage, $page, [
  2641. 'path' => Paginator::resolveCurrentPath(),
  2642. 'pageName' => $pageName,
  2643. ]);
  2644. }
  2645. /**
  2646. * Get a paginator only supporting simple next and previous links.
  2647. *
  2648. * This is more efficient on larger data-sets, etc.
  2649. *
  2650. * @param int|null $perPage
  2651. * @param array|string $columns
  2652. * @param string $cursorName
  2653. * @param \Illuminate\Pagination\Cursor|string|null $cursor
  2654. * @return \Illuminate\Contracts\Pagination\CursorPaginator
  2655. */
  2656. public function cursorPaginate($perPage = 15, $columns = ['*'], $cursorName = 'cursor', $cursor = null)
  2657. {
  2658. return $this->paginateUsingCursor($perPage, $columns, $cursorName, $cursor);
  2659. }
  2660. /**
  2661. * Ensure the proper order by required for cursor pagination.
  2662. *
  2663. * @param bool $shouldReverse
  2664. * @return \Illuminate\Support\Collection
  2665. */
  2666. protected function ensureOrderForCursorPagination($shouldReverse = false)
  2667. {
  2668. if (empty($this->orders) && empty($this->unionOrders)) {
  2669. $this->enforceOrderBy();
  2670. }
  2671. $reverseDirection = function ($order) {
  2672. if (! isset($order['direction'])) {
  2673. return $order;
  2674. }
  2675. $order['direction'] = $order['direction'] === 'asc' ? 'desc' : 'asc';
  2676. return $order;
  2677. };
  2678. if ($shouldReverse) {
  2679. $this->orders = collect($this->orders)->map($reverseDirection)->toArray();
  2680. $this->unionOrders = collect($this->unionOrders)->map($reverseDirection)->toArray();
  2681. }
  2682. $orders = ! empty($this->unionOrders) ? $this->unionOrders : $this->orders;
  2683. return collect($orders)
  2684. ->filter(fn ($order) => Arr::has($order, 'direction'))
  2685. ->values();
  2686. }
  2687. /**
  2688. * Get the count of the total records for the paginator.
  2689. *
  2690. * @param array $columns
  2691. * @return int
  2692. */
  2693. public function getCountForPagination($columns = ['*'])
  2694. {
  2695. $results = $this->runPaginationCountQuery($columns);
  2696. // Once we have run the pagination count query, we will get the resulting count and
  2697. // take into account what type of query it was. When there is a group by we will
  2698. // just return the count of the entire results set since that will be correct.
  2699. if (! isset($results[0])) {
  2700. return 0;
  2701. } elseif (is_object($results[0])) {
  2702. return (int) $results[0]->aggregate;
  2703. }
  2704. return (int) array_change_key_case((array) $results[0])['aggregate'];
  2705. }
  2706. /**
  2707. * Run a pagination count query.
  2708. *
  2709. * @param array $columns
  2710. * @return array
  2711. */
  2712. protected function runPaginationCountQuery($columns = ['*'])
  2713. {
  2714. if ($this->groups || $this->havings) {
  2715. $clone = $this->cloneForPaginationCount();
  2716. if (is_null($clone->columns) && ! empty($this->joins)) {
  2717. $clone->select($this->from.'.*');
  2718. }
  2719. return $this->newQuery()
  2720. ->from(new Expression('('.$clone->toSql().') as '.$this->grammar->wrap('aggregate_table')))
  2721. ->mergeBindings($clone)
  2722. ->setAggregate('count', $this->withoutSelectAliases($columns))
  2723. ->get()->all();
  2724. }
  2725. $without = $this->unions ? ['orders', 'limit', 'offset'] : ['columns', 'orders', 'limit', 'offset'];
  2726. return $this->cloneWithout($without)
  2727. ->cloneWithoutBindings($this->unions ? ['order'] : ['select', 'order'])
  2728. ->setAggregate('count', $this->withoutSelectAliases($columns))
  2729. ->get()->all();
  2730. }
  2731. /**
  2732. * Clone the existing query instance for usage in a pagination subquery.
  2733. *
  2734. * @return self
  2735. */
  2736. protected function cloneForPaginationCount()
  2737. {
  2738. return $this->cloneWithout(['orders', 'limit', 'offset'])
  2739. ->cloneWithoutBindings(['order']);
  2740. }
  2741. /**
  2742. * Remove the column aliases since they will break count queries.
  2743. *
  2744. * @param array $columns
  2745. * @return array
  2746. */
  2747. protected function withoutSelectAliases(array $columns)
  2748. {
  2749. return array_map(function ($column) {
  2750. return is_string($column) && ($aliasPosition = stripos($column, ' as ')) !== false
  2751. ? substr($column, 0, $aliasPosition) : $column;
  2752. }, $columns);
  2753. }
  2754. /**
  2755. * Get a lazy collection for the given query.
  2756. *
  2757. * @return \Illuminate\Support\LazyCollection
  2758. */
  2759. public function cursor()
  2760. {
  2761. if (is_null($this->columns)) {
  2762. $this->columns = ['*'];
  2763. }
  2764. return (new LazyCollection(function () {
  2765. yield from $this->connection->cursor(
  2766. $this->toSql(), $this->getBindings(), ! $this->useWritePdo
  2767. );
  2768. }))->map(function ($item) {
  2769. return $this->applyAfterQueryCallbacks(collect([$item]))->first();
  2770. })->reject(fn ($item) => is_null($item));
  2771. }
  2772. /**
  2773. * Throw an exception if the query doesn't have an orderBy clause.
  2774. *
  2775. * @return void
  2776. *
  2777. * @throws \RuntimeException
  2778. */
  2779. protected function enforceOrderBy()
  2780. {
  2781. if (empty($this->orders) && empty($this->unionOrders)) {
  2782. throw new RuntimeException('You must specify an orderBy clause when using this function.');
  2783. }
  2784. }
  2785. /**
  2786. * Get a collection instance containing the values of a given column.
  2787. *
  2788. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  2789. * @param string|null $key
  2790. * @return \Illuminate\Support\Collection
  2791. */
  2792. public function pluck($column, $key = null)
  2793. {
  2794. // First, we will need to select the results of the query accounting for the
  2795. // given columns / key. Once we have the results, we will be able to take
  2796. // the results and get the exact data that was requested for the query.
  2797. $queryResult = $this->onceWithColumns(
  2798. is_null($key) ? [$column] : [$column, $key],
  2799. function () {
  2800. return $this->processor->processSelect(
  2801. $this, $this->runSelect()
  2802. );
  2803. }
  2804. );
  2805. if (empty($queryResult)) {
  2806. return collect();
  2807. }
  2808. // If the columns are qualified with a table or have an alias, we cannot use
  2809. // those directly in the "pluck" operations since the results from the DB
  2810. // are only keyed by the column itself. We'll strip the table out here.
  2811. $column = $this->stripTableForPluck($column);
  2812. $key = $this->stripTableForPluck($key);
  2813. return $this->applyAfterQueryCallbacks(
  2814. is_array($queryResult[0])
  2815. ? $this->pluckFromArrayColumn($queryResult, $column, $key)
  2816. : $this->pluckFromObjectColumn($queryResult, $column, $key)
  2817. );
  2818. }
  2819. /**
  2820. * Strip off the table name or alias from a column identifier.
  2821. *
  2822. * @param string $column
  2823. * @return string|null
  2824. */
  2825. protected function stripTableForPluck($column)
  2826. {
  2827. if (is_null($column)) {
  2828. return $column;
  2829. }
  2830. $columnString = $column instanceof ExpressionContract
  2831. ? $this->grammar->getValue($column)
  2832. : $column;
  2833. $separator = str_contains(strtolower($columnString), ' as ') ? ' as ' : '\.';
  2834. return last(preg_split('~'.$separator.'~i', $columnString));
  2835. }
  2836. /**
  2837. * Retrieve column values from rows represented as objects.
  2838. *
  2839. * @param array $queryResult
  2840. * @param string $column
  2841. * @param string $key
  2842. * @return \Illuminate\Support\Collection
  2843. */
  2844. protected function pluckFromObjectColumn($queryResult, $column, $key)
  2845. {
  2846. $results = [];
  2847. if (is_null($key)) {
  2848. foreach ($queryResult as $row) {
  2849. $results[] = $row->$column;
  2850. }
  2851. } else {
  2852. foreach ($queryResult as $row) {
  2853. $results[$row->$key] = $row->$column;
  2854. }
  2855. }
  2856. return collect($results);
  2857. }
  2858. /**
  2859. * Retrieve column values from rows represented as arrays.
  2860. *
  2861. * @param array $queryResult
  2862. * @param string $column
  2863. * @param string $key
  2864. * @return \Illuminate\Support\Collection
  2865. */
  2866. protected function pluckFromArrayColumn($queryResult, $column, $key)
  2867. {
  2868. $results = [];
  2869. if (is_null($key)) {
  2870. foreach ($queryResult as $row) {
  2871. $results[] = $row[$column];
  2872. }
  2873. } else {
  2874. foreach ($queryResult as $row) {
  2875. $results[$row[$key]] = $row[$column];
  2876. }
  2877. }
  2878. return collect($results);
  2879. }
  2880. /**
  2881. * Concatenate values of a given column as a string.
  2882. *
  2883. * @param string $column
  2884. * @param string $glue
  2885. * @return string
  2886. */
  2887. public function implode($column, $glue = '')
  2888. {
  2889. return $this->pluck($column)->implode($glue);
  2890. }
  2891. /**
  2892. * Determine if any rows exist for the current query.
  2893. *
  2894. * @return bool
  2895. */
  2896. public function exists()
  2897. {
  2898. $this->applyBeforeQueryCallbacks();
  2899. $results = $this->connection->select(
  2900. $this->grammar->compileExists($this), $this->getBindings(), ! $this->useWritePdo
  2901. );
  2902. // If the results have rows, we will get the row and see if the exists column is a
  2903. // boolean true. If there are no results for this query we will return false as
  2904. // there are no rows for this query at all, and we can return that info here.
  2905. if (isset($results[0])) {
  2906. $results = (array) $results[0];
  2907. return (bool) $results['exists'];
  2908. }
  2909. return false;
  2910. }
  2911. /**
  2912. * Determine if no rows exist for the current query.
  2913. *
  2914. * @return bool
  2915. */
  2916. public function doesntExist()
  2917. {
  2918. return ! $this->exists();
  2919. }
  2920. /**
  2921. * Execute the given callback if no rows exist for the current query.
  2922. *
  2923. * @param \Closure $callback
  2924. * @return mixed
  2925. */
  2926. public function existsOr(Closure $callback)
  2927. {
  2928. return $this->exists() ? true : $callback();
  2929. }
  2930. /**
  2931. * Execute the given callback if rows exist for the current query.
  2932. *
  2933. * @param \Closure $callback
  2934. * @return mixed
  2935. */
  2936. public function doesntExistOr(Closure $callback)
  2937. {
  2938. return $this->doesntExist() ? true : $callback();
  2939. }
  2940. /**
  2941. * Retrieve the "count" result of the query.
  2942. *
  2943. * @param \Illuminate\Contracts\Database\Query\Expression|string $columns
  2944. * @return int
  2945. */
  2946. public function count($columns = '*')
  2947. {
  2948. return (int) $this->aggregate(__FUNCTION__, Arr::wrap($columns));
  2949. }
  2950. /**
  2951. * Retrieve the minimum value of a given column.
  2952. *
  2953. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  2954. * @return mixed
  2955. */
  2956. public function min($column)
  2957. {
  2958. return $this->aggregate(__FUNCTION__, [$column]);
  2959. }
  2960. /**
  2961. * Retrieve the maximum value of a given column.
  2962. *
  2963. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  2964. * @return mixed
  2965. */
  2966. public function max($column)
  2967. {
  2968. return $this->aggregate(__FUNCTION__, [$column]);
  2969. }
  2970. /**
  2971. * Retrieve the sum of the values of a given column.
  2972. *
  2973. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  2974. * @return mixed
  2975. */
  2976. public function sum($column)
  2977. {
  2978. $result = $this->aggregate(__FUNCTION__, [$column]);
  2979. return $result ?: 0;
  2980. }
  2981. /**
  2982. * Retrieve the average of the values of a given column.
  2983. *
  2984. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  2985. * @return mixed
  2986. */
  2987. public function avg($column)
  2988. {
  2989. return $this->aggregate(__FUNCTION__, [$column]);
  2990. }
  2991. /**
  2992. * Alias for the "avg" method.
  2993. *
  2994. * @param \Illuminate\Contracts\Database\Query\Expression|string $column
  2995. * @return mixed
  2996. */
  2997. public function average($column)
  2998. {
  2999. return $this->avg($column);
  3000. }
  3001. /**
  3002. * Execute an aggregate function on the database.
  3003. *
  3004. * @param string $function
  3005. * @param array $columns
  3006. * @return mixed
  3007. */
  3008. public function aggregate($function, $columns = ['*'])
  3009. {
  3010. $results = $this->cloneWithout($this->unions || $this->havings ? [] : ['columns'])
  3011. ->cloneWithoutBindings($this->unions || $this->havings ? [] : ['select'])
  3012. ->setAggregate($function, $columns)
  3013. ->get($columns);
  3014. if (! $results->isEmpty()) {
  3015. return array_change_key_case((array) $results[0])['aggregate'];
  3016. }
  3017. }
  3018. /**
  3019. * Execute a numeric aggregate function on the database.
  3020. *
  3021. * @param string $function
  3022. * @param array $columns
  3023. * @return float|int
  3024. */
  3025. public function numericAggregate($function, $columns = ['*'])
  3026. {
  3027. $result = $this->aggregate($function, $columns);
  3028. // If there is no result, we can obviously just return 0 here. Next, we will check
  3029. // if the result is an integer or float. If it is already one of these two data
  3030. // types we can just return the result as-is, otherwise we will convert this.
  3031. if (! $result) {
  3032. return 0;
  3033. }
  3034. if (is_int($result) || is_float($result)) {
  3035. return $result;
  3036. }
  3037. // If the result doesn't contain a decimal place, we will assume it is an int then
  3038. // cast it to one. When it does we will cast it to a float since it needs to be
  3039. // cast to the expected data type for the developers out of pure convenience.
  3040. return ! str_contains((string) $result, '.')
  3041. ? (int) $result : (float) $result;
  3042. }
  3043. /**
  3044. * Set the aggregate property without running the query.
  3045. *
  3046. * @param string $function
  3047. * @param array $columns
  3048. * @return $this
  3049. */
  3050. protected function setAggregate($function, $columns)
  3051. {
  3052. $this->aggregate = compact('function', 'columns');
  3053. if (empty($this->groups)) {
  3054. $this->orders = null;
  3055. $this->bindings['order'] = [];
  3056. }
  3057. return $this;
  3058. }
  3059. /**
  3060. * Execute the given callback while selecting the given columns.
  3061. *
  3062. * After running the callback, the columns are reset to the original value.
  3063. *
  3064. * @param array $columns
  3065. * @param callable $callback
  3066. * @return mixed
  3067. */
  3068. protected function onceWithColumns($columns, $callback)
  3069. {
  3070. $original = $this->columns;
  3071. if (is_null($original)) {
  3072. $this->columns = $columns;
  3073. }
  3074. $result = $callback();
  3075. $this->columns = $original;
  3076. return $result;
  3077. }
  3078. /**
  3079. * Insert new records into the database.
  3080. *
  3081. * @param array $values
  3082. * @return bool
  3083. */
  3084. public function insert(array $values)
  3085. {
  3086. // Since every insert gets treated like a batch insert, we will make sure the
  3087. // bindings are structured in a way that is convenient when building these
  3088. // inserts statements by verifying these elements are actually an array.
  3089. if (empty($values)) {
  3090. return true;
  3091. }
  3092. if (! is_array(reset($values))) {
  3093. $values = [$values];
  3094. }
  3095. // Here, we will sort the insert keys for every record so that each insert is
  3096. // in the same order for the record. We need to make sure this is the case
  3097. // so there are not any errors or problems when inserting these records.
  3098. else {
  3099. foreach ($values as $key => $value) {
  3100. ksort($value);
  3101. $values[$key] = $value;
  3102. }
  3103. }
  3104. $this->applyBeforeQueryCallbacks();
  3105. // Finally, we will run this query against the database connection and return
  3106. // the results. We will need to also flatten these bindings before running
  3107. // the query so they are all in one huge, flattened array for execution.
  3108. return $this->connection->insert(
  3109. $this->grammar->compileInsert($this, $values),
  3110. $this->cleanBindings(Arr::flatten($values, 1))
  3111. );
  3112. }
  3113. /**
  3114. * Insert new records into the database while ignoring errors.
  3115. *
  3116. * @param array $values
  3117. * @return int
  3118. */
  3119. public function insertOrIgnore(array $values)
  3120. {
  3121. if (empty($values)) {
  3122. return 0;
  3123. }
  3124. if (! is_array(reset($values))) {
  3125. $values = [$values];
  3126. } else {
  3127. foreach ($values as $key => $value) {
  3128. ksort($value);
  3129. $values[$key] = $value;
  3130. }
  3131. }
  3132. $this->applyBeforeQueryCallbacks();
  3133. return $this->connection->affectingStatement(
  3134. $this->grammar->compileInsertOrIgnore($this, $values),
  3135. $this->cleanBindings(Arr::flatten($values, 1))
  3136. );
  3137. }
  3138. /**
  3139. * Insert a new record and get the value of the primary key.
  3140. *
  3141. * @param array $values
  3142. * @param string|null $sequence
  3143. * @return int
  3144. */
  3145. public function insertGetId(array $values, $sequence = null)
  3146. {
  3147. $this->applyBeforeQueryCallbacks();
  3148. $sql = $this->grammar->compileInsertGetId($this, $values, $sequence);
  3149. $values = $this->cleanBindings($values);
  3150. return $this->processor->processInsertGetId($this, $sql, $values, $sequence);
  3151. }
  3152. /**
  3153. * Insert new records into the table using a subquery.
  3154. *
  3155. * @param array $columns
  3156. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  3157. * @return int
  3158. */
  3159. public function insertUsing(array $columns, $query)
  3160. {
  3161. $this->applyBeforeQueryCallbacks();
  3162. [$sql, $bindings] = $this->createSub($query);
  3163. return $this->connection->affectingStatement(
  3164. $this->grammar->compileInsertUsing($this, $columns, $sql),
  3165. $this->cleanBindings($bindings)
  3166. );
  3167. }
  3168. /**
  3169. * Insert new records into the table using a subquery while ignoring errors.
  3170. *
  3171. * @param array $columns
  3172. * @param \Closure|\Illuminate\Database\Query\Builder|\Illuminate\Database\Eloquent\Builder|string $query
  3173. * @return int
  3174. */
  3175. public function insertOrIgnoreUsing(array $columns, $query)
  3176. {
  3177. $this->applyBeforeQueryCallbacks();
  3178. [$sql, $bindings] = $this->createSub($query);
  3179. return $this->connection->affectingStatement(
  3180. $this->grammar->compileInsertOrIgnoreUsing($this, $columns, $sql),
  3181. $this->cleanBindings($bindings)
  3182. );
  3183. }
  3184. /**
  3185. * Update records in the database.
  3186. *
  3187. * @param array $values
  3188. * @return int
  3189. */
  3190. public function update(array $values)
  3191. {
  3192. $this->applyBeforeQueryCallbacks();
  3193. $values = collect($values)->map(function ($value) {
  3194. if (! $value instanceof Builder) {
  3195. return ['value' => $value, 'bindings' => $value];
  3196. }
  3197. [$query, $bindings] = $this->parseSub($value);
  3198. return ['value' => new Expression("({$query})"), 'bindings' => fn () => $bindings];
  3199. });
  3200. $sql = $this->grammar->compileUpdate($this, $values->map(fn ($value) => $value['value'])->all());
  3201. return $this->connection->update($sql, $this->cleanBindings(
  3202. $this->grammar->prepareBindingsForUpdate($this->bindings, $values->map(fn ($value) => $value['bindings'])->all())
  3203. ));
  3204. }
  3205. /**
  3206. * Update records in a PostgreSQL database using the update from syntax.
  3207. *
  3208. * @param array $values
  3209. * @return int
  3210. */
  3211. public function updateFrom(array $values)
  3212. {
  3213. if (! method_exists($this->grammar, 'compileUpdateFrom')) {
  3214. throw new LogicException('This database engine does not support the updateFrom method.');
  3215. }
  3216. $this->applyBeforeQueryCallbacks();
  3217. $sql = $this->grammar->compileUpdateFrom($this, $values);
  3218. return $this->connection->update($sql, $this->cleanBindings(
  3219. $this->grammar->prepareBindingsForUpdateFrom($this->bindings, $values)
  3220. ));
  3221. }
  3222. /**
  3223. * Insert or update a record matching the attributes, and fill it with values.
  3224. *
  3225. * @param array $attributes
  3226. * @param array|callable $values
  3227. * @return bool
  3228. */
  3229. public function updateOrInsert(array $attributes, array|callable $values = [])
  3230. {
  3231. $exists = $this->where($attributes)->exists();
  3232. if ($values instanceof Closure) {
  3233. $values = $values($exists);
  3234. }
  3235. if (! $exists) {
  3236. return $this->insert(array_merge($attributes, $values));
  3237. }
  3238. if (empty($values)) {
  3239. return true;
  3240. }
  3241. return (bool) $this->limit(1)->update($values);
  3242. }
  3243. /**
  3244. * Insert new records or update the existing ones.
  3245. *
  3246. * @param array $values
  3247. * @param array|string $uniqueBy
  3248. * @param array|null $update
  3249. * @return int
  3250. */
  3251. public function upsert(array $values, $uniqueBy, $update = null)
  3252. {
  3253. if (empty($values)) {
  3254. return 0;
  3255. } elseif ($update === []) {
  3256. return (int) $this->insert($values);
  3257. }
  3258. if (! is_array(reset($values))) {
  3259. $values = [$values];
  3260. } else {
  3261. foreach ($values as $key => $value) {
  3262. ksort($value);
  3263. $values[$key] = $value;
  3264. }
  3265. }
  3266. if (is_null($update)) {
  3267. $update = array_keys(reset($values));
  3268. }
  3269. $this->applyBeforeQueryCallbacks();
  3270. $bindings = $this->cleanBindings(array_merge(
  3271. Arr::flatten($values, 1),
  3272. collect($update)->reject(function ($value, $key) {
  3273. return is_int($key);
  3274. })->all()
  3275. ));
  3276. return $this->connection->affectingStatement(
  3277. $this->grammar->compileUpsert($this, $values, (array) $uniqueBy, $update),
  3278. $bindings
  3279. );
  3280. }
  3281. /**
  3282. * Increment a column's value by a given amount.
  3283. *
  3284. * @param string $column
  3285. * @param float|int $amount
  3286. * @param array $extra
  3287. * @return int
  3288. *
  3289. * @throws \InvalidArgumentException
  3290. */
  3291. public function increment($column, $amount = 1, array $extra = [])
  3292. {
  3293. if (! is_numeric($amount)) {
  3294. throw new InvalidArgumentException('Non-numeric value passed to increment method.');
  3295. }
  3296. return $this->incrementEach([$column => $amount], $extra);
  3297. }
  3298. /**
  3299. * Increment the given column's values by the given amounts.
  3300. *
  3301. * @param array<string, float|int|numeric-string> $columns
  3302. * @param array<string, mixed> $extra
  3303. * @return int
  3304. *
  3305. * @throws \InvalidArgumentException
  3306. */
  3307. public function incrementEach(array $columns, array $extra = [])
  3308. {
  3309. foreach ($columns as $column => $amount) {
  3310. if (! is_numeric($amount)) {
  3311. throw new InvalidArgumentException("Non-numeric value passed as increment amount for column: '$column'.");
  3312. } elseif (! is_string($column)) {
  3313. throw new InvalidArgumentException('Non-associative array passed to incrementEach method.');
  3314. }
  3315. $columns[$column] = $this->raw("{$this->grammar->wrap($column)} + $amount");
  3316. }
  3317. return $this->update(array_merge($columns, $extra));
  3318. }
  3319. /**
  3320. * Decrement a column's value by a given amount.
  3321. *
  3322. * @param string $column
  3323. * @param float|int $amount
  3324. * @param array $extra
  3325. * @return int
  3326. *
  3327. * @throws \InvalidArgumentException
  3328. */
  3329. public function decrement($column, $amount = 1, array $extra = [])
  3330. {
  3331. if (! is_numeric($amount)) {
  3332. throw new InvalidArgumentException('Non-numeric value passed to decrement method.');
  3333. }
  3334. return $this->decrementEach([$column => $amount], $extra);
  3335. }
  3336. /**
  3337. * Decrement the given column's values by the given amounts.
  3338. *
  3339. * @param array<string, float|int|numeric-string> $columns
  3340. * @param array<string, mixed> $extra
  3341. * @return int
  3342. *
  3343. * @throws \InvalidArgumentException
  3344. */
  3345. public function decrementEach(array $columns, array $extra = [])
  3346. {
  3347. foreach ($columns as $column => $amount) {
  3348. if (! is_numeric($amount)) {
  3349. throw new InvalidArgumentException("Non-numeric value passed as decrement amount for column: '$column'.");
  3350. } elseif (! is_string($column)) {
  3351. throw new InvalidArgumentException('Non-associative array passed to decrementEach method.');
  3352. }
  3353. $columns[$column] = $this->raw("{$this->grammar->wrap($column)} - $amount");
  3354. }
  3355. return $this->update(array_merge($columns, $extra));
  3356. }
  3357. /**
  3358. * Delete records from the database.
  3359. *
  3360. * @param mixed $id
  3361. * @return int
  3362. */
  3363. public function delete($id = null)
  3364. {
  3365. // If an ID is passed to the method, we will set the where clause to check the
  3366. // ID to let developers to simply and quickly remove a single row from this
  3367. // database without manually specifying the "where" clauses on the query.
  3368. if (! is_null($id)) {
  3369. $this->where($this->from.'.id', '=', $id);
  3370. }
  3371. $this->applyBeforeQueryCallbacks();
  3372. return $this->connection->delete(
  3373. $this->grammar->compileDelete($this), $this->cleanBindings(
  3374. $this->grammar->prepareBindingsForDelete($this->bindings)
  3375. )
  3376. );
  3377. }
  3378. /**
  3379. * Run a truncate statement on the table.
  3380. *
  3381. * @return void
  3382. */
  3383. public function truncate()
  3384. {
  3385. $this->applyBeforeQueryCallbacks();
  3386. foreach ($this->grammar->compileTruncate($this) as $sql => $bindings) {
  3387. $this->connection->statement($sql, $bindings);
  3388. }
  3389. }
  3390. /**
  3391. * Get a new instance of the query builder.
  3392. *
  3393. * @return \Illuminate\Database\Query\Builder
  3394. */
  3395. public function newQuery()
  3396. {
  3397. return new static($this->connection, $this->grammar, $this->processor);
  3398. }
  3399. /**
  3400. * Create a new query instance for a sub-query.
  3401. *
  3402. * @return \Illuminate\Database\Query\Builder
  3403. */
  3404. protected function forSubQuery()
  3405. {
  3406. return $this->newQuery();
  3407. }
  3408. /**
  3409. * Get all of the query builder's columns in a text-only array with all expressions evaluated.
  3410. *
  3411. * @return array
  3412. */
  3413. public function getColumns()
  3414. {
  3415. return ! is_null($this->columns)
  3416. ? array_map(fn ($column) => $this->grammar->getValue($column), $this->columns)
  3417. : [];
  3418. }
  3419. /**
  3420. * Create a raw database expression.
  3421. *
  3422. * @param mixed $value
  3423. * @return \Illuminate\Contracts\Database\Query\Expression
  3424. */
  3425. public function raw($value)
  3426. {
  3427. return $this->connection->raw($value);
  3428. }
  3429. /**
  3430. * Get the query builder instances that are used in the union of the query.
  3431. *
  3432. * @return \Illuminate\Support\Collection
  3433. */
  3434. protected function getUnionBuilders()
  3435. {
  3436. return isset($this->unions)
  3437. ? collect($this->unions)->pluck('query')
  3438. : collect();
  3439. }
  3440. /**
  3441. * Get the current query value bindings in a flattened array.
  3442. *
  3443. * @return array
  3444. */
  3445. public function getBindings()
  3446. {
  3447. return Arr::flatten($this->bindings);
  3448. }
  3449. /**
  3450. * Get the raw array of bindings.
  3451. *
  3452. * @return array
  3453. */
  3454. public function getRawBindings()
  3455. {
  3456. return $this->bindings;
  3457. }
  3458. /**
  3459. * Set the bindings on the query builder.
  3460. *
  3461. * @param array $bindings
  3462. * @param string $type
  3463. * @return $this
  3464. *
  3465. * @throws \InvalidArgumentException
  3466. */
  3467. public function setBindings(array $bindings, $type = 'where')
  3468. {
  3469. if (! array_key_exists($type, $this->bindings)) {
  3470. throw new InvalidArgumentException("Invalid binding type: {$type}.");
  3471. }
  3472. $this->bindings[$type] = $bindings;
  3473. return $this;
  3474. }
  3475. /**
  3476. * Add a binding to the query.
  3477. *
  3478. * @param mixed $value
  3479. * @param string $type
  3480. * @return $this
  3481. *
  3482. * @throws \InvalidArgumentException
  3483. */
  3484. public function addBinding($value, $type = 'where')
  3485. {
  3486. if (! array_key_exists($type, $this->bindings)) {
  3487. throw new InvalidArgumentException("Invalid binding type: {$type}.");
  3488. }
  3489. if (is_array($value)) {
  3490. $this->bindings[$type] = array_values(array_map(
  3491. [$this, 'castBinding'],
  3492. array_merge($this->bindings[$type], $value),
  3493. ));
  3494. } else {
  3495. $this->bindings[$type][] = $this->castBinding($value);
  3496. }
  3497. return $this;
  3498. }
  3499. /**
  3500. * Cast the given binding value.
  3501. *
  3502. * @param mixed $value
  3503. * @return mixed
  3504. */
  3505. public function castBinding($value)
  3506. {
  3507. if ($value instanceof UnitEnum) {
  3508. return $value instanceof BackedEnum ? $value->value : $value->name;
  3509. }
  3510. return $value;
  3511. }
  3512. /**
  3513. * Merge an array of bindings into our bindings.
  3514. *
  3515. * @param \Illuminate\Database\Query\Builder $query
  3516. * @return $this
  3517. */
  3518. public function mergeBindings(self $query)
  3519. {
  3520. $this->bindings = array_merge_recursive($this->bindings, $query->bindings);
  3521. return $this;
  3522. }
  3523. /**
  3524. * Remove all of the expressions from a list of bindings.
  3525. *
  3526. * @param array $bindings
  3527. * @return array
  3528. */
  3529. public function cleanBindings(array $bindings)
  3530. {
  3531. return collect($bindings)
  3532. ->reject(function ($binding) {
  3533. return $binding instanceof ExpressionContract;
  3534. })
  3535. ->map([$this, 'castBinding'])
  3536. ->values()
  3537. ->all();
  3538. }
  3539. /**
  3540. * Get a scalar type value from an unknown type of input.
  3541. *
  3542. * @param mixed $value
  3543. * @return mixed
  3544. */
  3545. protected function flattenValue($value)
  3546. {
  3547. return is_array($value) ? head(Arr::flatten($value)) : $value;
  3548. }
  3549. /**
  3550. * Get the default key name of the table.
  3551. *
  3552. * @return string
  3553. */
  3554. protected function defaultKeyName()
  3555. {
  3556. return 'id';
  3557. }
  3558. /**
  3559. * Get the database connection instance.
  3560. *
  3561. * @return \Illuminate\Database\ConnectionInterface
  3562. */
  3563. public function getConnection()
  3564. {
  3565. return $this->connection;
  3566. }
  3567. /**
  3568. * Get the database query processor instance.
  3569. *
  3570. * @return \Illuminate\Database\Query\Processors\Processor
  3571. */
  3572. public function getProcessor()
  3573. {
  3574. return $this->processor;
  3575. }
  3576. /**
  3577. * Get the query grammar instance.
  3578. *
  3579. * @return \Illuminate\Database\Query\Grammars\Grammar
  3580. */
  3581. public function getGrammar()
  3582. {
  3583. return $this->grammar;
  3584. }
  3585. /**
  3586. * Use the "write" PDO connection when executing the query.
  3587. *
  3588. * @return $this
  3589. */
  3590. public function useWritePdo()
  3591. {
  3592. $this->useWritePdo = true;
  3593. return $this;
  3594. }
  3595. /**
  3596. * Determine if the value is a query builder instance or a Closure.
  3597. *
  3598. * @param mixed $value
  3599. * @return bool
  3600. */
  3601. protected function isQueryable($value)
  3602. {
  3603. return $value instanceof self ||
  3604. $value instanceof EloquentBuilder ||
  3605. $value instanceof Relation ||
  3606. $value instanceof Closure;
  3607. }
  3608. /**
  3609. * Clone the query.
  3610. *
  3611. * @return static
  3612. */
  3613. public function clone()
  3614. {
  3615. return clone $this;
  3616. }
  3617. /**
  3618. * Clone the query without the given properties.
  3619. *
  3620. * @param array $properties
  3621. * @return static
  3622. */
  3623. public function cloneWithout(array $properties)
  3624. {
  3625. return tap($this->clone(), function ($clone) use ($properties) {
  3626. foreach ($properties as $property) {
  3627. $clone->{$property} = null;
  3628. }
  3629. });
  3630. }
  3631. /**
  3632. * Clone the query without the given bindings.
  3633. *
  3634. * @param array $except
  3635. * @return static
  3636. */
  3637. public function cloneWithoutBindings(array $except)
  3638. {
  3639. return tap($this->clone(), function ($clone) use ($except) {
  3640. foreach ($except as $type) {
  3641. $clone->bindings[$type] = [];
  3642. }
  3643. });
  3644. }
  3645. /**
  3646. * Dump the current SQL and bindings.
  3647. *
  3648. * @param mixed ...$args
  3649. * @return $this
  3650. */
  3651. public function dump(...$args)
  3652. {
  3653. dump(
  3654. $this->toSql(),
  3655. $this->getBindings(),
  3656. ...$args,
  3657. );
  3658. return $this;
  3659. }
  3660. /**
  3661. * Dump the raw current SQL with embedded bindings.
  3662. *
  3663. * @return $this
  3664. */
  3665. public function dumpRawSql()
  3666. {
  3667. dump($this->toRawSql());
  3668. return $this;
  3669. }
  3670. /**
  3671. * Die and dump the current SQL and bindings.
  3672. *
  3673. * @return never
  3674. */
  3675. public function dd()
  3676. {
  3677. dd($this->toSql(), $this->getBindings());
  3678. }
  3679. /**
  3680. * Die and dump the current SQL with embedded bindings.
  3681. *
  3682. * @return never
  3683. */
  3684. public function ddRawSql()
  3685. {
  3686. dd($this->toRawSql());
  3687. }
  3688. /**
  3689. * Handle dynamic method calls into the method.
  3690. *
  3691. * @param string $method
  3692. * @param array $parameters
  3693. * @return mixed
  3694. *
  3695. * @throws \BadMethodCallException
  3696. */
  3697. public function __call($method, $parameters)
  3698. {
  3699. if (static::hasMacro($method)) {
  3700. return $this->macroCall($method, $parameters);
  3701. }
  3702. if (str_starts_with($method, 'where')) {
  3703. return $this->dynamicWhere($method, $parameters);
  3704. }
  3705. static::throwBadMethodCallException($method);
  3706. }
  3707. }