query.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. <?php namespace Laravel\Database;
  2. use Closure;
  3. use Laravel\Database;
  4. use Laravel\Paginator;
  5. use Laravel\Database\Query\Grammars\Grammar;
  6. use Laravel\Database\Query\Grammars\SQLServer;
  7. class Query {
  8. /**
  9. * The database connection.
  10. *
  11. * @var Connection
  12. */
  13. public $connection;
  14. /**
  15. * The query grammar instance.
  16. *
  17. * @var Query\Grammars\Grammar
  18. */
  19. public $grammar;
  20. /**
  21. * The SELECT clause.
  22. *
  23. * @var array
  24. */
  25. public $selects;
  26. /**
  27. * The aggregating column and function.
  28. *
  29. * @var array
  30. */
  31. public $aggregate;
  32. /**
  33. * Indicates if the query should return distinct results.
  34. *
  35. * @var bool
  36. */
  37. public $distinct = false;
  38. /**
  39. * The table name.
  40. *
  41. * @var string
  42. */
  43. public $from;
  44. /**
  45. * The table joins.
  46. *
  47. * @var array
  48. */
  49. public $joins;
  50. /**
  51. * The WHERE clauses.
  52. *
  53. * @var array
  54. */
  55. public $wheres;
  56. /**
  57. * The GROUP BY clauses.
  58. *
  59. * @var array
  60. */
  61. public $groupings;
  62. /**
  63. * The ORDER BY clauses.
  64. *
  65. * @var array
  66. */
  67. public $orderings;
  68. /**
  69. * The LIMIT value.
  70. *
  71. * @var int
  72. */
  73. public $limit;
  74. /**
  75. * The OFFSET value.
  76. *
  77. * @var int
  78. */
  79. public $offset;
  80. /**
  81. * The query value bindings.
  82. *
  83. * @var array
  84. */
  85. public $bindings = array();
  86. /**
  87. * Create a new query instance.
  88. *
  89. * @param Connection $connection
  90. * @param Grammar $grammar
  91. * @param string $table
  92. * @return void
  93. */
  94. public function __construct(Connection $connection, Grammar $grammar, $table)
  95. {
  96. $this->from = $table;
  97. $this->grammar = $grammar;
  98. $this->connection = $connection;
  99. }
  100. /**
  101. * Force the query to return distinct results.
  102. *
  103. * @return Query
  104. */
  105. public function distinct()
  106. {
  107. $this->distinct = true;
  108. return $this;
  109. }
  110. /**
  111. * Add an array of columns to the SELECT clause.
  112. *
  113. * @param array $columns
  114. * @return Query
  115. */
  116. public function select($columns = array('*'))
  117. {
  118. $this->selects = (array) $columns;
  119. return $this;
  120. }
  121. /**
  122. * Add a join clause to the query.
  123. *
  124. * @param string $table
  125. * @param string $column1
  126. * @param string $operator
  127. * @param string $column2
  128. * @param string $type
  129. * @return Query
  130. */
  131. public function join($table, $column1, $operator, $column2, $type = 'INNER')
  132. {
  133. $this->joins[] = compact('type', 'table', 'column1', 'operator', 'column2');
  134. return $this;
  135. }
  136. /**
  137. * Add a left join to the query.
  138. *
  139. * @param string $table
  140. * @param string $column1
  141. * @param string $operator
  142. * @param string $column2
  143. * @return Query
  144. */
  145. public function left_join($table, $column1, $operator, $column2)
  146. {
  147. return $this->join($table, $column1, $operator, $column2, 'LEFT');
  148. }
  149. /**
  150. * Reset the where clause to its initial state.
  151. *
  152. * @return void
  153. */
  154. public function reset_where()
  155. {
  156. list($this->wheres, $this->bindings) = array(array(), array());
  157. }
  158. /**
  159. * Add a raw where condition to the query.
  160. *
  161. * @param string $where
  162. * @param array $bindings
  163. * @param string $connector
  164. * @return Query
  165. */
  166. public function raw_where($where, $bindings = array(), $connector = 'AND')
  167. {
  168. $this->wheres[] = array('type' => 'where_raw', 'connector' => $connector, 'sql' => $where);
  169. $this->bindings = array_merge($this->bindings, $bindings);
  170. return $this;
  171. }
  172. /**
  173. * Add a raw or where condition to the query.
  174. *
  175. * @param string $where
  176. * @param array $bindings
  177. * @return Query
  178. */
  179. public function raw_or_where($where, $bindings = array())
  180. {
  181. return $this->raw_where($where, $bindings, 'OR');
  182. }
  183. /**
  184. * Add a where condition to the query.
  185. *
  186. * @param string $column
  187. * @param string $operator
  188. * @param mixed $value
  189. * @param string $connector
  190. * @return Query
  191. */
  192. public function where($column, $operator = null, $value = null, $connector = 'AND')
  193. {
  194. // If a CLosure is passed into the method, it means a nested where
  195. // clause is being initiated, so we will take a different course
  196. // of action than when the statement is just a simple where.
  197. if ($column instanceof Closure)
  198. {
  199. return $this->where_nested($column, $connector);
  200. }
  201. $type = 'where';
  202. $this->wheres[] = compact('type', 'column', 'operator', 'value', 'connector');
  203. $this->bindings[] = $value;
  204. return $this;
  205. }
  206. /**
  207. * Add an or where condition to the query.
  208. *
  209. * @param string $column
  210. * @param string $operator
  211. * @param mixed $value
  212. * @return Query
  213. */
  214. public function or_where($column, $operator = null, $value = null)
  215. {
  216. return $this->where($column, $operator, $value, 'OR');
  217. }
  218. /**
  219. * Add an or where condition for the primary key to the query.
  220. *
  221. * @param mixed $value
  222. * @return Query
  223. */
  224. public function or_where_id($value)
  225. {
  226. return $this->or_where('id', '=', $value);
  227. }
  228. /**
  229. * Add a where in condition to the query.
  230. *
  231. * @param string $column
  232. * @param array $values
  233. * @param string $connector
  234. * @param bool $not
  235. * @return Query
  236. */
  237. public function where_in($column, $values, $connector = 'AND', $not = false)
  238. {
  239. $type = ($not) ? 'where_not_in' : 'where_in';
  240. $this->wheres[] = compact('type', 'column', 'values', 'connector');
  241. $this->bindings = array_merge($this->bindings, $values);
  242. return $this;
  243. }
  244. /**
  245. * Add an or where in condition to the query.
  246. *
  247. * @param string $column
  248. * @param array $values
  249. * @return Query
  250. */
  251. public function or_where_in($column, $values)
  252. {
  253. return $this->where_in($column, $values, 'OR');
  254. }
  255. /**
  256. * Add a where not in condition to the query.
  257. *
  258. * @param string $column
  259. * @param array $values
  260. * @param string $connector
  261. * @return Query
  262. */
  263. public function where_not_in($column, $values, $connector = 'AND')
  264. {
  265. return $this->where_in($column, $values, $connector, true);
  266. }
  267. /**
  268. * Add an or where not in condition to the query.
  269. *
  270. * @param string $column
  271. * @param array $values
  272. * @return Query
  273. */
  274. public function or_where_not_in($column, $values)
  275. {
  276. return $this->where_not_in($column, $values, 'OR');
  277. }
  278. /**
  279. * Add a where null condition to the query.
  280. *
  281. * @param string $column
  282. * @param string $connector
  283. * @param bool $not
  284. * @return Query
  285. */
  286. public function where_null($column, $connector = 'AND', $not = false)
  287. {
  288. $type = ($not) ? 'where_not_null' : 'where_null';
  289. $this->wheres[] = compact('type', 'column', 'connector');
  290. return $this;
  291. }
  292. /**
  293. * Add an or where null condition to the query.
  294. *
  295. * @param string $column
  296. * @return Query
  297. */
  298. public function or_where_null($column)
  299. {
  300. return $this->where_null($column, 'OR');
  301. }
  302. /**
  303. * Add a where not null condition to the query.
  304. *
  305. * @param string $column
  306. * @param string $connector
  307. * @return Query
  308. */
  309. public function where_not_null($column, $connector = 'AND')
  310. {
  311. return $this->where_null($column, $connector, true);
  312. }
  313. /**
  314. * Add an or where not null condition to the query.
  315. *
  316. * @param string $column
  317. * @return Query
  318. */
  319. public function or_where_not_null($column)
  320. {
  321. return $this->where_not_null($column, 'OR');
  322. }
  323. /**
  324. * Add a nested where condition to the query.
  325. *
  326. * @param Closure $callback
  327. * @param string $connector
  328. * @return Query
  329. */
  330. protected function where_nested($callback, $connector)
  331. {
  332. $type = 'where_nested';
  333. // To handle a nested where statement, we will actually instantiate a
  334. // new Query instance and run the callback over that instance, which
  335. // will allow the developer to have a fresh query to work with.
  336. $query = new Query($this->connection, $this->grammar, $this->from);
  337. // Once the callback has been run on the query, we will store the
  338. // nested query instance on the where clause array so that it's
  339. // passed to the query grammar.
  340. call_user_func($callback, $query);
  341. $this->wheres[] = compact('type', 'query', 'connector');
  342. $this->bindings = array_merge($this->bindings, $query->bindings);
  343. return $this;
  344. }
  345. /**
  346. * Add dynamic where conditions to the query.
  347. *
  348. * @param string $method
  349. * @param array $parameters
  350. * @return Query
  351. */
  352. private function dynamic_where($method, $parameters)
  353. {
  354. $finder = substr($method, 6);
  355. $flags = PREG_SPLIT_DELIM_CAPTURE;
  356. $segments = preg_split('/(_and_|_or_)/i', $finder, -1, $flags);
  357. // The connector variable will determine which connector will be
  358. // used for the condition. We'll change it as we come across new
  359. // connectors in the dynamic method string.
  360. //
  361. // The index variable helps us get the correct parameter value
  362. // for the where condition. We increment it each time we add
  363. // a condition to the query.
  364. $connector = 'AND';
  365. $index = 0;
  366. foreach ($segments as $segment)
  367. {
  368. // If the segment is not a boolean connector, we can assume it
  369. // it is a column name, and we'll add it to the query as a new
  370. // where clause.
  371. //
  372. // Otherwise, we'll store the connector so that we know how to
  373. // connection the next where clause we find to the query, as
  374. // all connectors should precede a new where clause.
  375. if ($segment != '_and_' and $segment != '_or_')
  376. {
  377. $this->where($segment, '=', $parameters[$index], $connector);
  378. $index++;
  379. }
  380. else
  381. {
  382. $connector = trim(strtoupper($segment), '_');
  383. }
  384. }
  385. return $this;
  386. }
  387. /**
  388. * Add a grouping to the query.
  389. *
  390. * @param string $column
  391. * @return Query
  392. */
  393. public function group_by($column)
  394. {
  395. $this->groupings[] = $column;
  396. return $this;
  397. }
  398. /**
  399. * Add an ordering to the query.
  400. *
  401. * @param string $column
  402. * @param string $direction
  403. * @return Query
  404. */
  405. public function order_by($column, $direction = 'asc')
  406. {
  407. $this->orderings[] = compact('column', 'direction');
  408. return $this;
  409. }
  410. /**
  411. * Set the query offset.
  412. *
  413. * @param int $value
  414. * @return Query
  415. */
  416. public function skip($value)
  417. {
  418. $this->offset = $value;
  419. return $this;
  420. }
  421. /**
  422. * Set the query limit.
  423. *
  424. * @param int $value
  425. * @return Query
  426. */
  427. public function take($value)
  428. {
  429. $this->limit = $value;
  430. return $this;
  431. }
  432. /**
  433. * Set the query limit and offset for a given page.
  434. *
  435. * @param int $page
  436. * @param int $per_page
  437. * @return Query
  438. */
  439. public function for_page($page, $per_page)
  440. {
  441. return $this->skip(($page - 1) * $per_page)->take($per_page);
  442. }
  443. /**
  444. * Find a record by the primary key.
  445. *
  446. * @param int $id
  447. * @param array $columns
  448. * @return object
  449. */
  450. public function find($id, $columns = array('*'))
  451. {
  452. return $this->where('id', '=', $id)->first($columns);
  453. }
  454. /**
  455. * Execute the query as a SELECT statement and return a single column.
  456. *
  457. * @param string $column
  458. * @return mixed
  459. */
  460. public function only($column)
  461. {
  462. $sql = $this->grammar->select($this->select(array($column)));
  463. return $this->connection->only($sql, $this->bindings);
  464. }
  465. /**
  466. * Execute the query as a SELECT statement and return the first result.
  467. *
  468. * @param array $columns
  469. * @return mixed
  470. */
  471. public function first($columns = array('*'))
  472. {
  473. $columns = (array) $columns;
  474. // Since we only need the first result, we'll go ahead and set the
  475. // limit clause to 1, since this will be much faster than getting
  476. // all of the rows and then only returning the first.
  477. $results = $this->take(1)->get($columns);
  478. return (count($results) > 0) ? $results[0] : null;
  479. }
  480. /**
  481. * Get an array with the values of a given column.
  482. *
  483. * @param string $column
  484. * @param string $key
  485. * @return array
  486. */
  487. public function lists($column, $key = null)
  488. {
  489. $columns = (is_null($key)) ? array($column) : array($column, $key);
  490. $results = $this->get($columns);
  491. // First we will get the array of values for the requested column.
  492. // Of course, this array will simply have numeric keys. After we
  493. // have this array we will determine if we need to key the array
  494. // by another column from the result set.
  495. $values = array_map(function($row) use ($column)
  496. {
  497. return $row->$column;
  498. }, $results);
  499. // If a key was provided, we will extract an array of keys and
  500. // set the keys on the array of values using the array_combine
  501. // function provided by PHP, which should give us the proper
  502. // array form to return from the method.
  503. if ( ! is_null($key))
  504. {
  505. return array_combine(array_map(function($row) use ($key)
  506. {
  507. return $row->$key;
  508. }, $results), $values);
  509. }
  510. return $values;
  511. }
  512. /**
  513. * Execute the query as a SELECT statement.
  514. *
  515. * @param array $columns
  516. * @return array
  517. */
  518. public function get($columns = array('*'))
  519. {
  520. if (is_null($this->selects)) $this->select($columns);
  521. $sql = $this->grammar->select($this);
  522. $results = $this->connection->query($sql, $this->bindings);
  523. // If the query has an offset and we are using the SQL Server grammar,
  524. // we need to spin through the results and remove the "rownum" from
  525. // each of the objects. Unfortunately SQL Server does not have an
  526. // offset keyword, so we have to use row numbers in the query.
  527. if ($this->offset > 0 and $this->grammar instanceof SQLServer)
  528. {
  529. array_walk($results, function($result)
  530. {
  531. unset($result->rownum);
  532. });
  533. }
  534. // Reset the SELECT clause so more queries can be performed using
  535. // the same instance. This is helpful for getting aggregates and
  536. // then getting actual results from the query.
  537. $this->selects = null;
  538. return $results;
  539. }
  540. /**
  541. * Get an aggregate value.
  542. *
  543. * @param string $aggregate
  544. * @param string $column
  545. * @return mixed
  546. */
  547. private function aggregate($aggregator, $column)
  548. {
  549. $this->aggregate = compact('aggregator', 'column');
  550. $sql = $this->grammar->select($this);
  551. $result = $this->connection->only($sql, $this->bindings);
  552. // Reset the aggregate so more queries can be performed using
  553. // the same instance. This is helpful for getting aggregates
  554. // and then getting actual results from the query.
  555. $this->aggregate = null;
  556. return $result;
  557. }
  558. /**
  559. * Get the paginated query results as a Paginator instance.
  560. *
  561. * @param int $per_page
  562. * @param array $columns
  563. * @return Paginator
  564. */
  565. public function paginate($per_page = 20, $columns = array('*'))
  566. {
  567. // Because some database engines may throw errors if we leave orderings
  568. // on the query when retrieving the total number of records, we will
  569. // remove all of the ordreings and put them back on the query after
  570. // we have the count.
  571. list($orderings, $this->orderings) = array($this->orderings, null);
  572. $page = Paginator::page($total = $this->count(), $per_page);
  573. $this->orderings = $orderings;
  574. // Now we're ready to get the actual pagination results from the
  575. // database table. The "for_page" method provides a convenient
  576. // way to set the limit and offset so we get the correct span
  577. // of results from the table.
  578. $results = $this->for_page($page, $per_page)->get($columns);
  579. return Paginator::make($results, $total, $per_page);
  580. }
  581. /**
  582. * Insert an array of values into the database table.
  583. *
  584. * @param array $values
  585. * @return bool
  586. */
  587. public function insert($values)
  588. {
  589. // Force every insert to be treated like a batch insert to make creating
  590. // the binding array simpler since we can just spin through the inserted
  591. // rows as if there/ was more than one every time.
  592. if ( ! is_array(reset($values))) $values = array($values);
  593. $bindings = array();
  594. // We need to merge the the insert values into the array of the query
  595. // bindings so that they will be bound to the PDO statement when it
  596. // is executed by the database connection.
  597. foreach ($values as $value)
  598. {
  599. $bindings = array_merge($bindings, array_values($value));
  600. }
  601. $sql = $this->grammar->insert($this, $values);
  602. return $this->connection->statement($sql, $bindings);
  603. }
  604. /**
  605. * Insert an array of values into the database table and return the ID.
  606. *
  607. * @param array $values
  608. * @param string $sequence
  609. * @return int
  610. */
  611. public function insert_get_id($values, $sequence = null)
  612. {
  613. $sql = $this->grammar->insert($this, $values);
  614. $this->connection->statement($sql, array_values($values));
  615. // Some database systems (Postgres) require a sequence name to be
  616. // given when retrieving the auto-incrementing ID, so we'll pass
  617. // the given sequence into the method just in case.
  618. return (int) $this->connection->pdo->lastInsertId($sequence);
  619. }
  620. /**
  621. * Increment the value of a column by a given amount.
  622. *
  623. * @param string $column
  624. * @param int $amount
  625. * @return int
  626. */
  627. public function increment($column, $amount = 1)
  628. {
  629. return $this->adjust($column, $amount, ' + ');
  630. }
  631. /**
  632. * Decrement the value of a column by a given amount.
  633. *
  634. * @param string $column
  635. * @param int $amount
  636. * @return int
  637. */
  638. public function decrement($column, $amount = 1)
  639. {
  640. return $this->adjust($column, $amount, ' - ');
  641. }
  642. /**
  643. * Adjust the value of a column up or down by a given amount.
  644. *
  645. * @param string $column
  646. * @param int $amount
  647. * @param string $operator
  648. * @return int
  649. */
  650. protected function adjust($column, $amount, $operator)
  651. {
  652. // To make the adjustment to the column, we'll wrap the expression
  653. // in an Expression instance, which forces the adjustment to be
  654. // injected into the query as a string instead of bound.
  655. $value = Database::raw($this->grammar->wrap($column).$operator.$amount);
  656. return $this->update(array($column => $value));
  657. }
  658. /**
  659. * Update an array of values in the database table.
  660. *
  661. * @param array $values
  662. * @return int
  663. */
  664. public function update($values)
  665. {
  666. // For update statements, we need to merge the bindings such that
  667. // the update values occur before the where bindings in the array
  668. // since the set statements will precede any of the where clauses
  669. // in the SQL syntax that is generated.
  670. $bindings = array_merge(array_values($values), $this->bindings);
  671. $sql = $this->grammar->update($this, $values);
  672. return $this->connection->update($sql, $bindings);
  673. }
  674. /**
  675. * Execute the query as a DELETE statement.
  676. *
  677. * Optionally, an ID may be passed to the method do delete a specific row.
  678. *
  679. * @param int $id
  680. * @return int
  681. */
  682. public function delete($id = null)
  683. {
  684. // If an ID is given to the method, we'll set the where clause
  685. // to match on the value of the ID. This allows the developer
  686. // to quickly delete a row by its primary key value.
  687. if ( ! is_null($id))
  688. {
  689. $this->where('id', '=', $id);
  690. }
  691. $sql = $this->grammar->delete($this);
  692. return $this->connection->delete($sql, $this->bindings);
  693. }
  694. /**
  695. * Magic Method for handling dynamic functions.
  696. *
  697. * This method handles calls to aggregates as well as dynamic where clauses.
  698. */
  699. public function __call($method, $parameters)
  700. {
  701. if (strpos($method, 'where_') === 0)
  702. {
  703. return $this->dynamic_where($method, $parameters, $this);
  704. }
  705. if (in_array($method, array('count', 'min', 'max', 'avg', 'sum')))
  706. {
  707. if ($method == 'count')
  708. {
  709. return $this->aggregate(strtoupper($method), '*');
  710. }
  711. else
  712. {
  713. return $this->aggregate(strtoupper($method), $parameters[0]);
  714. }
  715. }
  716. throw new \Exception("Method [$method] is not defined on the Query class.");
  717. }
  718. }