query.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. <?php namespace Laravel\Database;
  2. class Query {
  3. /**
  4. * The database connection.
  5. *
  6. * @var Connection
  7. */
  8. public $connection;
  9. /**
  10. * The query compiler instance.
  11. *
  12. * @var Compiler
  13. */
  14. public $compiler;
  15. /**
  16. * The SELECT clause.
  17. *
  18. * @var array
  19. */
  20. public $select;
  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 $table;
  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 Compiler $compiler
  81. * @param string $table
  82. * @return void
  83. */
  84. public function __construct(Connection $connection, Query\Compiler $compiler, $table)
  85. {
  86. $this->table = $table;
  87. $this->compiler = $compiler;
  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. * <code>
  104. * $query->select(array('id', 'email'));
  105. * </code>
  106. *
  107. * @param array $columns
  108. * @return Query
  109. */
  110. public function select($columns = array('*'))
  111. {
  112. $this->select = $columns;
  113. return $this;
  114. }
  115. /**
  116. * Add a join clause to the query.
  117. *
  118. * <code>
  119. * $query->join('users', 'users.id', '=', 'posts.user_id');
  120. * </code>
  121. *
  122. * @param string $table
  123. * @param string $column1
  124. * @param string $operator
  125. * @param string $column2
  126. * @param string $type
  127. * @return Query
  128. */
  129. public function join($table, $column1, $operator, $column2, $type = 'INNER')
  130. {
  131. $this->joins[] = compact('table', 'column1', 'operator', 'column2', 'type');
  132. return $this;
  133. }
  134. /**
  135. * Add a left join to the query.
  136. *
  137. * <code>
  138. * $query->left_join('users', 'users.id', '=', 'posts.user_id');
  139. * </code>
  140. *
  141. * @param string $table
  142. * @param string $column1
  143. * @param string $operator
  144. * @param string $column2
  145. * @return Query
  146. */
  147. public function left_join($table, $column1, $operator, $column2)
  148. {
  149. return $this->join($table, $column1, $operator, $column2, 'LEFT');
  150. }
  151. /**
  152. * Reset the where clause to its initial state. All bindings will be cleared.
  153. *
  154. * @return void
  155. */
  156. public function reset_where()
  157. {
  158. $this->wheres = array();
  159. $this->bindings = array();
  160. }
  161. /**
  162. * Add a raw where condition to the query.
  163. *
  164. * <code>
  165. * $query->raw_where('user_id = ? and password = ?', array(1, 'secret'));
  166. * </code>
  167. *
  168. * @param string $where
  169. * @param array $bindings
  170. * @param string $connector
  171. * @return Query
  172. */
  173. public function raw_where($where, $bindings = array(), $connector = 'AND')
  174. {
  175. $this->wheres[] = ' '.$connector.' '.$where;
  176. $this->bindings = array_merge($this->bindings, $bindings);
  177. return $this;
  178. }
  179. /**
  180. * Add a raw or where condition to the query.
  181. *
  182. * <code>
  183. * $query->raw_or_where('user_id = ? and password = ?', array(1, 'secret'));
  184. * </code>
  185. *
  186. * @param string $where
  187. * @param array $bindings
  188. * @return Query
  189. */
  190. public function raw_or_where($where, $bindings = array())
  191. {
  192. return $this->raw_where($where, $bindings, 'OR');
  193. }
  194. /**
  195. * Add a where condition to the query.
  196. *
  197. * <code>
  198. * $query->where('id', '=', 1);
  199. * </code>
  200. *
  201. * @param string $column
  202. * @param string $operator
  203. * @param mixed $value
  204. * @param string $connector
  205. * @return Query
  206. */
  207. public function where($column, $operator, $value, $connector = 'AND')
  208. {
  209. $this->wheres[] = array_merge(array('type' => 'where'), compact('column', 'operator', 'value', 'connector'));
  210. $this->bindings[] = $value;
  211. return $this;
  212. }
  213. /**
  214. * Add an or where condition to the query.
  215. *
  216. * <code>
  217. * $query->or_where('id', '=', 1);
  218. * </code>
  219. *
  220. * @param string $column
  221. * @param string $operator
  222. * @param mixed $value
  223. * @return Query
  224. */
  225. public function or_where($column, $operator, $value)
  226. {
  227. return $this->where($column, $operator, $value, 'OR');
  228. }
  229. /**
  230. * Add a where condition for the primary key to the query.
  231. *
  232. * <code>
  233. * $query->where_id(1);
  234. * </code>
  235. *
  236. * @param mixed $value
  237. * @return Query
  238. */
  239. public function where_id($value)
  240. {
  241. return $this->where('id', '=', $value);
  242. }
  243. /**
  244. * Add an or where condition for the primary key to the query.
  245. *
  246. * <code>
  247. * $query->or_where_id(1);
  248. * </code>
  249. *
  250. * @param mixed $value
  251. * @return Query
  252. */
  253. public function or_where_id($value)
  254. {
  255. return $this->or_where('id', '=', $value);
  256. }
  257. /**
  258. * Add a where in condition to the query.
  259. *
  260. * <code>
  261. * $query->where_in('id', array(1, 2, 3));
  262. * </code>
  263. *
  264. * @param string $column
  265. * @param array $values
  266. * @param string $connector
  267. * @param bool $not
  268. * @return Query
  269. */
  270. public function where_in($column, $values, $connector = 'AND', $not = false)
  271. {
  272. $this->wheres[] = array_merge(array('type' => 'where_in'), compact('column', 'values', 'connector', 'not'));
  273. $this->bindings = array_merge($this->bindings, $values);
  274. return $this;
  275. }
  276. /**
  277. * Add an or where in condition to the query.
  278. *
  279. * <code>
  280. * $query->or_where_in('id', array(1, 2, 3));
  281. * </code>
  282. *
  283. * @param string $column
  284. * @param array $values
  285. * @return Query
  286. */
  287. public function or_where_in($column, $values)
  288. {
  289. return $this->where_in($column, $values, 'OR');
  290. }
  291. /**
  292. * Add a where not in condition to the query.
  293. *
  294. * <code>
  295. * $query->where_not_in('id', array(1, 2, 3));
  296. * </code>
  297. *
  298. * @param string $column
  299. * @param array $values
  300. * @param string $connector
  301. * @return Query
  302. */
  303. public function where_not_in($column, $values, $connector = 'AND')
  304. {
  305. return $this->where_in($column, $values, $connector, true);
  306. }
  307. /**
  308. * Add an or where not in condition to the query.
  309. *
  310. * <code>
  311. * $query->or_where_not_in('id', array(1, 2, 3));
  312. * </code>
  313. *
  314. * @param string $column
  315. * @param array $values
  316. * @return Query
  317. */
  318. public function or_where_not_in($column, $values)
  319. {
  320. return $this->where_not_in($column, $values, 'OR');
  321. }
  322. /**
  323. * Add a where null condition to the query.
  324. *
  325. * @param string $column
  326. * @param string $connector
  327. * @param bool $not
  328. * @return Query
  329. */
  330. public function where_null($column, $connector = 'AND', $not = false)
  331. {
  332. $this->wheres[] = array_merge(array('type' => 'where_null'), compact('column', 'connector', 'not'));
  333. return $this;
  334. }
  335. /**
  336. * Add an or where null condition to the query.
  337. *
  338. * @param string $column
  339. * @return Query
  340. */
  341. public function or_where_null($column)
  342. {
  343. return $this->where_null($column, 'OR');
  344. }
  345. /**
  346. * Add a where not null condition to the query.
  347. *
  348. * @param string $column
  349. * @param string $connector
  350. * @return Query
  351. */
  352. public function where_not_null($column, $connector = 'AND')
  353. {
  354. return $this->where_null($column, $connector, true);
  355. }
  356. /**
  357. * Add an or where not null condition to the query.
  358. *
  359. * @param string $column
  360. * @return Query
  361. */
  362. public function or_where_not_null($column)
  363. {
  364. return $this->where_not_null($column, 'OR');
  365. }
  366. /**
  367. * Add dynamic where conditions to the query.
  368. *
  369. * Dynamic queries are caught by the __call magic method and are parsed here.
  370. * They provide a convenient, expressive API for building simple conditions.
  371. *
  372. * @param string $method
  373. * @param array $parameters
  374. * @return Query
  375. */
  376. private function dynamic_where($method, $parameters)
  377. {
  378. // Strip the "where_" off of the method.
  379. $finder = substr($method, 6);
  380. // Split the column names from the connectors.
  381. $segments = preg_split('/(_and_|_or_)/i', $finder, -1, PREG_SPLIT_DELIM_CAPTURE);
  382. // The connector variable will determine which connector will be used for the condition.
  383. // We'll change it as we come across new connectors in the dynamic method string.
  384. //
  385. // The index variable helps us get the correct parameter value for the where condition.
  386. // We increment it each time we add a condition.
  387. $connector = 'AND';
  388. $index = 0;
  389. foreach ($segments as $segment)
  390. {
  391. if ($segment != '_and_' and $segment != '_or_')
  392. {
  393. $this->where($segment, '=', $parameters[$index], $connector);
  394. $index++;
  395. }
  396. else
  397. {
  398. $connector = trim(strtoupper($segment), '_');
  399. }
  400. }
  401. return $this;
  402. }
  403. /**
  404. * Add an ordering to the query.
  405. *
  406. * <code>
  407. * // Set an ascending sort on the query
  408. * $query->order_by('votes', 'asc');
  409. *
  410. * // Set a descending sort on the query
  411. * $query->order_by('votes', 'desc');
  412. * </code>
  413. *
  414. * @param string $column
  415. * @param string $direction
  416. * @return Query
  417. */
  418. public function order_by($column, $direction = 'asc')
  419. {
  420. $this->orderings[] = compact('column', 'direction');
  421. return $this;
  422. }
  423. /**
  424. * Set the query offset.
  425. *
  426. * @param int $value
  427. * @return Query
  428. */
  429. public function skip($value)
  430. {
  431. $this->offset = $value;
  432. return $this;
  433. }
  434. /**
  435. * Set the query limit.
  436. *
  437. * @param int $value
  438. * @return Query
  439. */
  440. public function take($value)
  441. {
  442. $this->limit = $value;
  443. return $this;
  444. }
  445. /**
  446. * Set the query limit and offset for a given page and item per page count.
  447. *
  448. * If the given page is not an integer or is less than zero, one will be used.
  449. *
  450. * <code>
  451. * // Get the the 15 users that should be displayed for page 1
  452. * $results = DB::table('users')->for_page(1, 15);
  453. * </code>
  454. *
  455. * @param int $page
  456. * @param int $per_page
  457. * @return Query
  458. */
  459. public function for_page($page, $per_page)
  460. {
  461. if ($page < 1 or filter_var($page, FILTER_VALIDATE_INT) === false) $page = 1;
  462. return $this->skip(($page - 1) * $per_page)->take($per_page);
  463. }
  464. /**
  465. * Find a record by the primary key.
  466. *
  467. * <code>
  468. * // Get the user having an ID of 1
  469. * $user = DB::table('users')->find(1);
  470. * </code>
  471. *
  472. * @param int $id
  473. * @param array $columns
  474. * @return object
  475. */
  476. public function find($id, $columns = array('*'))
  477. {
  478. return $this->where('id', '=', $id)->first($columns);
  479. }
  480. /**
  481. * Get an aggregate value.
  482. *
  483. * @param string $aggregate
  484. * @param string $column
  485. * @return mixed
  486. */
  487. private function aggregate($aggregator, $column)
  488. {
  489. $this->aggregate = compact('aggregator', 'column');
  490. $result = $this->connection->scalar($this->compiler->select($this), $this->bindings);
  491. // Reset the SELECT clause so more queries can be performed using the same instance.
  492. // This is helpful for getting aggregates and then getting actual results.
  493. $this->select = null;
  494. return $result;
  495. }
  496. /**
  497. * Execute the query as a SELECT statement and return the first result.
  498. *
  499. * @param array $columns
  500. * @return stdClass
  501. */
  502. public function first($columns = array('*'))
  503. {
  504. return (count($results = $this->take(1)->get($columns)) > 0) ? $results[0] : null;
  505. }
  506. /**
  507. * Execute the query as a SELECT statement.
  508. *
  509. * @param array $columns
  510. * @return array
  511. */
  512. public function get($columns = array('*'))
  513. {
  514. if (is_null($this->select)) $this->select($columns);
  515. $results = $this->connection->query($this->compiler->select($this), $this->bindings);
  516. // Reset the SELECT clause so more queries can be performed using the same instance.
  517. // This is helpful for getting aggregates and then getting actual results.
  518. $this->select = null;
  519. return $results;
  520. }
  521. /**
  522. * Insert an array of values into the database table.
  523. *
  524. * <code>
  525. * // Insert into the "users" table
  526. * $success = DB::table('users')->insert(array('id' => 1, 'email' => 'example@gmail.com'));
  527. * </code>
  528. *
  529. * @param array $values
  530. * @return bool
  531. */
  532. public function insert($values)
  533. {
  534. return $this->connection->query($this->compiler->insert($this, $values), array_values($values));
  535. }
  536. /**
  537. * Insert an array of values into the database table and return the value of the ID column.
  538. *
  539. * <code>
  540. * // Insert into the "users" table and get the auto-incrementing ID
  541. * $id = DB::table('users')->insert_get_id(array('email' => 'example@gmail.com'));
  542. * </code>
  543. *
  544. * @param array $values
  545. * @return int
  546. */
  547. public function insert_get_id($values)
  548. {
  549. $this->connection->query($this->compiler->insert($this, $values), array_values($values));
  550. return (int) $this->connection->pdo->lastInsertId();
  551. }
  552. /**
  553. * Update an array of values in the database table.
  554. *
  555. * <code>
  556. * // Update a user's e-mail address
  557. * $affected = DB::table('users')->where_id(1)->update(array('email' => 'new_email@example.com'));
  558. * </code>
  559. *
  560. * @param array $values
  561. * @return int
  562. */
  563. public function update($values)
  564. {
  565. return $this->connection->query($this->compiler->update($this, $values), array_merge(array_values($values), $this->bindings));
  566. }
  567. /**
  568. * Execute the query as a DELETE statement.
  569. *
  570. * Optionally, an ID may be passed to the method do delete a specific row.
  571. *
  572. * <code>
  573. * // Delete everything from the "users" table
  574. * $affected = DB::table('users')->delete();
  575. *
  576. * // Delete a specific user from the table
  577. * $affected = DB::table('users')->delete(1);
  578. *
  579. * // Execute a delete statement with where conditions
  580. * $affected = DB::table('users')->where_email($email)->delete();
  581. * </code>
  582. *
  583. * @param int $id
  584. * @return int
  585. */
  586. public function delete($id = null)
  587. {
  588. if ( ! is_null($id)) $this->where('id', '=', $id);
  589. return $this->connection->query($this->compiler->delete($this), $this->bindings);
  590. }
  591. /**
  592. * Magic Method for handling dynamic functions.
  593. *
  594. * This method handles all calls to aggregate functions as well as the construction of dynamic where clauses.
  595. *
  596. * <code>
  597. * // Get the total number of rows on the "users" table
  598. * $count = DB::table('users')->count();
  599. *
  600. * // Get a user using a dynamic where clause
  601. * $user = DB::table('users')->where_email('example@gmail.com')->first();
  602. * </code>
  603. */
  604. public function __call($method, $parameters)
  605. {
  606. if (strpos($method, 'where_') === 0)
  607. {
  608. return $this->dynamic_where($method, $parameters, $this);
  609. }
  610. if (in_array($method, array('count', 'min', 'max', 'avg', 'sum')))
  611. {
  612. return ($method == 'count') ? $this->aggregate(strtoupper($method), '*') : $this->aggregate(strtoupper($method), $parameters[0]);
  613. }
  614. throw new \Exception("Method [$method] is not defined on the Query class.");
  615. }
  616. }