query.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. <?php namespace Laravel\Database; use Laravel\Paginator;
  2. class Query {
  3. /**
  4. * The database connection.
  5. *
  6. * @var Connection
  7. */
  8. public $connection;
  9. /**
  10. * The query grammar instance.
  11. *
  12. * @var Grammars\Grammar
  13. */
  14. public $grammar;
  15. /**
  16. * The SELECT clause.
  17. *
  18. * @var array
  19. */
  20. public $selects;
  21. /**
  22. * If the query is performing an aggregate function, this will contain the column
  23. * and and function to use when aggregating.
  24. *
  25. * @var array
  26. */
  27. public $aggregate;
  28. /**
  29. * Indicates if the query should return distinct results.
  30. *
  31. * @var bool
  32. */
  33. public $distinct = false;
  34. /**
  35. * The table name.
  36. *
  37. * @var string
  38. */
  39. public $from;
  40. /**
  41. * The table joins.
  42. *
  43. * @var array
  44. */
  45. public $joins;
  46. /**
  47. * The WHERE clauses.
  48. *
  49. * @var array
  50. */
  51. public $wheres;
  52. /**
  53. * The ORDER BY clauses.
  54. *
  55. * @var array
  56. */
  57. public $orderings;
  58. /**
  59. * The LIMIT value.
  60. *
  61. * @var int
  62. */
  63. public $limit;
  64. /**
  65. * The OFFSET value.
  66. *
  67. * @var int
  68. */
  69. public $offset;
  70. /**
  71. * The query value bindings.
  72. *
  73. * @var array
  74. */
  75. public $bindings = array();
  76. /**
  77. * Create a new query instance.
  78. *
  79. * @param Connection $connection
  80. * @param Grammars\Grammar $grammar
  81. * @param string $table
  82. * @return void
  83. */
  84. public function __construct(Connection $connection, Grammars\Grammar $grammar, $table)
  85. {
  86. $this->from = $table;
  87. $this->grammar = $grammar;
  88. $this->connection = $connection;
  89. }
  90. /**
  91. * Force the query to return distinct results.
  92. *
  93. * @return Query
  94. */
  95. public function distinct()
  96. {
  97. $this->distinct = true;
  98. return $this;
  99. }
  100. /**
  101. * Add an array of columns to the SELECT clause.
  102. *
  103. * @param array $columns
  104. * @return Query
  105. */
  106. public function select($columns = array('*'))
  107. {
  108. $this->selects = (array) $columns;
  109. return $this;
  110. }
  111. /**
  112. * Add a join clause to the query.
  113. *
  114. * @param string $table
  115. * @param string $column1
  116. * @param string $operator
  117. * @param string $column2
  118. * @param string $type
  119. * @return Query
  120. */
  121. public function join($table, $column1, $operator, $column2, $type = 'INNER')
  122. {
  123. $this->joins[] = compact('type', 'table', 'column1', 'operator', 'column2');
  124. return $this;
  125. }
  126. /**
  127. * Add a left join to the query.
  128. *
  129. * @param string $table
  130. * @param string $column1
  131. * @param string $operator
  132. * @param string $column2
  133. * @return Query
  134. */
  135. public function left_join($table, $column1, $operator, $column2)
  136. {
  137. return $this->join($table, $column1, $operator, $column2, 'LEFT');
  138. }
  139. /**
  140. * Reset the where clause to its initial state. All bindings will be cleared.
  141. *
  142. * @return void
  143. */
  144. public function reset_where()
  145. {
  146. list($this->wheres, $this->bindings) = array(array(), array());
  147. }
  148. /**
  149. * Add a raw where condition to the query.
  150. *
  151. * @param string $where
  152. * @param array $bindings
  153. * @param string $connector
  154. * @return Query
  155. */
  156. public function raw_where($where, $bindings = array(), $connector = 'AND')
  157. {
  158. $this->wheres[] = array('type' => 'raw', 'connector' => $connector, 'sql' => $where);
  159. $this->bindings = array_merge($this->bindings, $bindings);
  160. return $this;
  161. }
  162. /**
  163. * Add a raw or where condition to the query.
  164. *
  165. * @param string $where
  166. * @param array $bindings
  167. * @return Query
  168. */
  169. public function raw_or_where($where, $bindings = array())
  170. {
  171. return $this->raw_where($where, $bindings, 'OR');
  172. }
  173. /**
  174. * Add a where condition to the query.
  175. *
  176. * @param string $column
  177. * @param string $operator
  178. * @param mixed $value
  179. * @param string $connector
  180. * @return Query
  181. */
  182. public function where($column, $operator, $value, $connector = 'AND')
  183. {
  184. $this->wheres[] = array_merge(array('type' => 'where'), compact('column', 'operator', 'value', 'connector'));
  185. $this->bindings[] = $value;
  186. return $this;
  187. }
  188. /**
  189. * Add an or where condition to the query.
  190. *
  191. * @param string $column
  192. * @param string $operator
  193. * @param mixed $value
  194. * @return Query
  195. */
  196. public function or_where($column, $operator, $value)
  197. {
  198. return $this->where($column, $operator, $value, 'OR');
  199. }
  200. /**
  201. * Add an or where condition for the primary key to the query.
  202. *
  203. * @param mixed $value
  204. * @return Query
  205. */
  206. public function or_where_id($value)
  207. {
  208. return $this->or_where('id', '=', $value);
  209. }
  210. /**
  211. * Add a where in condition to the query.
  212. *
  213. * @param string $column
  214. * @param array $values
  215. * @param string $connector
  216. * @param bool $not
  217. * @return Query
  218. */
  219. public function where_in($column, $values, $connector = 'AND', $not = false)
  220. {
  221. $this->wheres[] = array_merge(array('type' => 'where_in'), compact('column', 'values', 'connector', 'not'));
  222. $this->bindings = array_merge($this->bindings, $values);
  223. return $this;
  224. }
  225. /**
  226. * Add an or where in condition to the query.
  227. *
  228. * @param string $column
  229. * @param array $values
  230. * @return Query
  231. */
  232. public function or_where_in($column, $values)
  233. {
  234. return $this->where_in($column, $values, 'OR');
  235. }
  236. /**
  237. * Add a where not in condition to the query.
  238. *
  239. * @param string $column
  240. * @param array $values
  241. * @param string $connector
  242. * @return Query
  243. */
  244. public function where_not_in($column, $values, $connector = 'AND')
  245. {
  246. return $this->where_in($column, $values, $connector, true);
  247. }
  248. /**
  249. * Add an or where not in condition to the query.
  250. *
  251. * @param string $column
  252. * @param array $values
  253. * @return Query
  254. */
  255. public function or_where_not_in($column, $values)
  256. {
  257. return $this->where_not_in($column, $values, 'OR');
  258. }
  259. /**
  260. * Add a where null condition to the query.
  261. *
  262. * @param string $column
  263. * @param string $connector
  264. * @param bool $not
  265. * @return Query
  266. */
  267. public function where_null($column, $connector = 'AND', $not = false)
  268. {
  269. $this->wheres[] = array_merge(array('type' => 'where_null'), compact('column', 'connector', 'not'));
  270. return $this;
  271. }
  272. /**
  273. * Add an or where null condition to the query.
  274. *
  275. * @param string $column
  276. * @return Query
  277. */
  278. public function or_where_null($column)
  279. {
  280. return $this->where_null($column, 'OR');
  281. }
  282. /**
  283. * Add a where not null condition to the query.
  284. *
  285. * @param string $column
  286. * @param string $connector
  287. * @return Query
  288. */
  289. public function where_not_null($column, $connector = 'AND')
  290. {
  291. return $this->where_null($column, $connector, true);
  292. }
  293. /**
  294. * Add an or where not null condition to the query.
  295. *
  296. * @param string $column
  297. * @return Query
  298. */
  299. public function or_where_not_null($column)
  300. {
  301. return $this->where_not_null($column, 'OR');
  302. }
  303. /**
  304. * Add dynamic where conditions to the query.
  305. *
  306. * Dynamic queries are caught by the __call magic method and are parsed here.
  307. * They provide a convenient, expressive API for building simple conditions.
  308. *
  309. * @param string $method
  310. * @param array $parameters
  311. * @return Query
  312. */
  313. private function dynamic_where($method, $parameters)
  314. {
  315. // Strip the "where_" off of the method.
  316. $finder = substr($method, 6);
  317. // Split the column names from the connectors.
  318. $segments = preg_split('/(_and_|_or_)/i', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);
  319. // The connector variable will determine which connector will be used for the condition.
  320. // We'll change it as we come across new connectors in the dynamic method string.
  321. //
  322. // The index variable helps us get the correct parameter value for the where condition.
  323. // We increment it each time we add a condition.
  324. $connector = 'AND';
  325. $index = 0;
  326. foreach ($segments as $segment)
  327. {
  328. if ($segment != '_and_' and $segment != '_or_')
  329. {
  330. $this->where($segment, '=', $parameters[$index], $connector);
  331. $index++;
  332. }
  333. else
  334. {
  335. $connector = trim(strtoupper($segment), '_');
  336. }
  337. }
  338. return $this;
  339. }
  340. /**
  341. * Add an ordering to the query.
  342. *
  343. * @param string $column
  344. * @param string $direction
  345. * @return Query
  346. */
  347. public function order_by($column, $direction = 'asc')
  348. {
  349. $this->orderings[] = compact('column', 'direction');
  350. return $this;
  351. }
  352. /**
  353. * Set the query offset.
  354. *
  355. * @param int $value
  356. * @return Query
  357. */
  358. public function skip($value)
  359. {
  360. $this->offset = $value;
  361. return $this;
  362. }
  363. /**
  364. * Set the query limit.
  365. *
  366. * @param int $value
  367. * @return Query
  368. */
  369. public function take($value)
  370. {
  371. $this->limit = $value;
  372. return $this;
  373. }
  374. /**
  375. * Set the query limit and offset for a given page and item per page count.
  376. *
  377. * @param int $page
  378. * @param int $per_page
  379. * @return Query
  380. */
  381. public function for_page($page, $per_page)
  382. {
  383. return $this->skip(($page - 1) * $per_page)->take($per_page);
  384. }
  385. /**
  386. * Find a record by the primary key.
  387. *
  388. * @param int $id
  389. * @param array $columns
  390. * @return object
  391. */
  392. public function find($id, $columns = array('*'))
  393. {
  394. return $this->where('id', '=', $id)->first($columns);
  395. }
  396. /**
  397. * Execute the query as a SELECT statement and return a single column.
  398. *
  399. * @param string $column
  400. * @return mixed
  401. */
  402. public function only($column)
  403. {
  404. $this->select(array($column));
  405. return $this->connection->only($this->grammar->select($this), $this->bindings);
  406. }
  407. /**
  408. * Execute the query as a SELECT statement and return the first result.
  409. *
  410. * If a single column is selected from the database, only the value of that column will be returned.
  411. *
  412. * @param array $columns
  413. * @return mixed
  414. */
  415. public function first($columns = array('*'))
  416. {
  417. $columns = (array) $columns;
  418. return (count($results = $this->take(1)->get($columns)) > 0) ? $results[0] : null;
  419. }
  420. /**
  421. * Execute the query as a SELECT statement.
  422. *
  423. * @param array $columns
  424. * @return array
  425. */
  426. public function get($columns = array('*'))
  427. {
  428. if (is_null($this->selects)) $this->select($columns);
  429. $results = $this->connection->query($this->grammar->select($this), $this->bindings);
  430. // Reset the SELECT clause so more queries can be performed using the same instance.
  431. // This is helpful for getting aggregates and then getting actual results.
  432. $this->selects = null;
  433. return $results;
  434. }
  435. /**
  436. * Get an aggregate value.
  437. *
  438. * @param string $aggregate
  439. * @param string $column
  440. * @return mixed
  441. */
  442. private function aggregate($aggregator, $column)
  443. {
  444. $this->aggregate = compact('aggregator', 'column');
  445. $result = $this->connection->only($this->grammar->select($this), $this->bindings);
  446. // Reset the aggregate so more queries can be performed using the same instance.
  447. // This is helpful for getting aggregates and then getting actual results.
  448. $this->aggregate = null;
  449. return $result;
  450. }
  451. /**
  452. * Get the paginated query results as a Paginator instance.
  453. *
  454. * @param int $per_page
  455. * @param array $columns
  456. * @return Paginator
  457. */
  458. public function paginate($per_page = 20, $columns = array('*'))
  459. {
  460. // Calculate the current page for the request. The page number will be validated
  461. // and adjusted by the Paginator class, so we can assume it is valid.
  462. $page = Paginator::page($total = $this->count(), $per_page);
  463. return Paginator::make($this->for_page($page, $per_page)->get($columns), $total, $per_page);
  464. }
  465. /**
  466. * Insert an array of values into the database table.
  467. *
  468. * @param array $values
  469. * @return bool
  470. */
  471. public function insert($values)
  472. {
  473. // Force every insert to be treated like a batch insert. This simply makes creating
  474. // the binding array easier. We will simply loop through each inserted row and merge
  475. // the values together to get one big binding array.
  476. if ( ! is_array(reset($values))) $values = array($values);
  477. $bindings = array();
  478. foreach ($values as $value)
  479. {
  480. $bindings = array_merge($bindings, array_values($value));
  481. }
  482. return $this->connection->query($this->grammar->insert($this, $values), $bindings);
  483. }
  484. /**
  485. * Insert an array of values into the database table and return the value of the ID column.
  486. *
  487. * @param array $values
  488. * @param string $sequence
  489. * @return int
  490. */
  491. public function insert_get_id($values, $sequence = null)
  492. {
  493. $this->connection->query($this->grammar->insert($this, $values), array_values($values));
  494. return (int) $this->connection->pdo->lastInsertId($sequence);
  495. }
  496. /**
  497. * Update an array of values in the database table.
  498. *
  499. * @param array $values
  500. * @return int
  501. */
  502. public function update($values)
  503. {
  504. return $this->connection->query($this->grammar->update($this, $values), array_merge(array_values($values), $this->bindings));
  505. }
  506. /**
  507. * Execute the query as a DELETE statement.
  508. *
  509. * Optionally, an ID may be passed to the method do delete a specific row.
  510. *
  511. * @param int $id
  512. * @return int
  513. */
  514. public function delete($id = null)
  515. {
  516. if ( ! is_null($id)) $this->where('id', '=', $id);
  517. return $this->connection->query($this->grammar->delete($this), $this->bindings);
  518. }
  519. /**
  520. * Magic Method for handling dynamic functions.
  521. *
  522. * This method handles all calls to aggregate functions as well as the construction
  523. * of dynamic where clauses via the "dynamic_where" method.
  524. */
  525. public function __call($method, $parameters)
  526. {
  527. if (strpos($method, 'where_') === 0)
  528. {
  529. return $this->dynamic_where($method, $parameters, $this);
  530. }
  531. if (in_array($method, array('abs', 'count', 'min', 'max', 'avg', 'sum')))
  532. {
  533. return ($method == 'count') ? $this->aggregate(strtoupper($method), '*') : $this->aggregate(strtoupper($method), $parameters[0]);
  534. }
  535. throw new \Exception("Method [$method] is not defined on the Query class.");
  536. }
  537. }