You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

922 lines
36KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\db;
  8. use Yii;
  9. use yii\base\Component;
  10. /**
  11. * Query represents a SELECT SQL statement in a way that is independent of DBMS.
  12. *
  13. * Query provides a set of methods to facilitate the specification of different clauses
  14. * in a SELECT statement. These methods can be chained together.
  15. *
  16. * By calling [[createCommand()]], we can get a [[Command]] instance which can be further
  17. * used to perform/execute the DB query against a database.
  18. *
  19. * For example,
  20. *
  21. * ```php
  22. * $query = new Query;
  23. * // compose the query
  24. * $query->select('id, name')
  25. * ->from('user')
  26. * ->limit(10);
  27. * // build and execute the query
  28. * $rows = $query->all();
  29. * // alternatively, you can create DB command and execute it
  30. * $command = $query->createCommand();
  31. * // $command->sql returns the actual SQL
  32. * $rows = $command->queryAll();
  33. * ```
  34. *
  35. * Query internally uses the [[QueryBuilder]] class to generate the SQL statement.
  36. *
  37. * A more detailed usage guide on how to work with Query can be found in the [guide article on Query Builder](guide:db-query-builder).
  38. *
  39. * @author Qiang Xue <qiang.xue@gmail.com>
  40. * @author Carsten Brandt <mail@cebe.cc>
  41. * @since 2.0
  42. */
  43. class Query extends Component implements QueryInterface
  44. {
  45. use QueryTrait;
  46. /**
  47. * @var array the columns being selected. For example, `['id', 'name']`.
  48. * This is used to construct the SELECT clause in a SQL statement. If not set, it means selecting all columns.
  49. * @see select()
  50. */
  51. public $select;
  52. /**
  53. * @var string additional option that should be appended to the 'SELECT' keyword. For example,
  54. * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
  55. */
  56. public $selectOption;
  57. /**
  58. * @var boolean whether to select distinct rows of data only. If this is set true,
  59. * the SELECT clause would be changed to SELECT DISTINCT.
  60. */
  61. public $distinct;
  62. /**
  63. * @var array the table(s) to be selected from. For example, `['user', 'post']`.
  64. * This is used to construct the FROM clause in a SQL statement.
  65. * @see from()
  66. */
  67. public $from;
  68. /**
  69. * @var array how to group the query results. For example, `['company', 'department']`.
  70. * This is used to construct the GROUP BY clause in a SQL statement.
  71. */
  72. public $groupBy;
  73. /**
  74. * @var array how to join with other tables. Each array element represents the specification
  75. * of one join which has the following structure:
  76. *
  77. * ```php
  78. * [$joinType, $tableName, $joinCondition]
  79. * ```
  80. *
  81. * For example,
  82. *
  83. * ```php
  84. * [
  85. * ['INNER JOIN', 'user', 'user.id = author_id'],
  86. * ['LEFT JOIN', 'team', 'team.id = team_id'],
  87. * ]
  88. * ```
  89. */
  90. public $join;
  91. /**
  92. * @var string|array|Expression the condition to be applied in the GROUP BY clause.
  93. * It can be either a string or an array. Please refer to [[where()]] on how to specify the condition.
  94. */
  95. public $having;
  96. /**
  97. * @var array this is used to construct the UNION clause(s) in a SQL statement.
  98. * Each array element is an array of the following structure:
  99. *
  100. * - `query`: either a string or a [[Query]] object representing a query
  101. * - `all`: boolean, whether it should be `UNION ALL` or `UNION`
  102. */
  103. public $union;
  104. /**
  105. * @var array list of query parameter values indexed by parameter placeholders.
  106. * For example, `[':name' => 'Dan', ':age' => 31]`.
  107. */
  108. public $params = [];
  109. /**
  110. * Creates a DB command that can be used to execute this query.
  111. * @param Connection $db the database connection used to generate the SQL statement.
  112. * If this parameter is not given, the `db` application component will be used.
  113. * @return Command the created DB command instance.
  114. */
  115. public function createCommand($db = null)
  116. {
  117. if ($db === null) {
  118. $db = Yii::$app->getDb();
  119. }
  120. list ($sql, $params) = $db->getQueryBuilder()->build($this);
  121. return $db->createCommand($sql, $params);
  122. }
  123. /**
  124. * Prepares for building SQL.
  125. * This method is called by [[QueryBuilder]] when it starts to build SQL from a query object.
  126. * You may override this method to do some final preparation work when converting a query into a SQL statement.
  127. * @param QueryBuilder $builder
  128. * @return $this a prepared query instance which will be used by [[QueryBuilder]] to build the SQL
  129. */
  130. public function prepare($builder)
  131. {
  132. return $this;
  133. }
  134. /**
  135. * Starts a batch query.
  136. *
  137. * A batch query supports fetching data in batches, which can keep the memory usage under a limit.
  138. * This method will return a [[BatchQueryResult]] object which implements the [[\Iterator]] interface
  139. * and can be traversed to retrieve the data in batches.
  140. *
  141. * For example,
  142. *
  143. * ```php
  144. * $query = (new Query)->from('user');
  145. * foreach ($query->batch() as $rows) {
  146. * // $rows is an array of 100 or fewer rows from user table
  147. * }
  148. * ```
  149. *
  150. * @param integer $batchSize the number of records to be fetched in each batch.
  151. * @param Connection $db the database connection. If not set, the "db" application component will be used.
  152. * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
  153. * and can be traversed to retrieve the data in batches.
  154. */
  155. public function batch($batchSize = 100, $db = null)
  156. {
  157. return Yii::createObject([
  158. 'class' => BatchQueryResult::className(),
  159. 'query' => $this,
  160. 'batchSize' => $batchSize,
  161. 'db' => $db,
  162. 'each' => false,
  163. ]);
  164. }
  165. /**
  166. * Starts a batch query and retrieves data row by row.
  167. * This method is similar to [[batch()]] except that in each iteration of the result,
  168. * only one row of data is returned. For example,
  169. *
  170. * ```php
  171. * $query = (new Query)->from('user');
  172. * foreach ($query->each() as $row) {
  173. * }
  174. * ```
  175. *
  176. * @param integer $batchSize the number of records to be fetched in each batch.
  177. * @param Connection $db the database connection. If not set, the "db" application component will be used.
  178. * @return BatchQueryResult the batch query result. It implements the [[\Iterator]] interface
  179. * and can be traversed to retrieve the data in batches.
  180. */
  181. public function each($batchSize = 100, $db = null)
  182. {
  183. return Yii::createObject([
  184. 'class' => BatchQueryResult::className(),
  185. 'query' => $this,
  186. 'batchSize' => $batchSize,
  187. 'db' => $db,
  188. 'each' => true,
  189. ]);
  190. }
  191. /**
  192. * Executes the query and returns all results as an array.
  193. * @param Connection $db the database connection used to generate the SQL statement.
  194. * If this parameter is not given, the `db` application component will be used.
  195. * @return array the query results. If the query results in nothing, an empty array will be returned.
  196. */
  197. public function all($db = null)
  198. {
  199. $rows = $this->createCommand($db)->queryAll();
  200. return $this->populate($rows);
  201. }
  202. /**
  203. * Converts the raw query results into the format as specified by this query.
  204. * This method is internally used to convert the data fetched from database
  205. * into the format as required by this query.
  206. * @param array $rows the raw query result from database
  207. * @return array the converted query result
  208. */
  209. public function populate($rows)
  210. {
  211. if ($this->indexBy === null) {
  212. return $rows;
  213. }
  214. $result = [];
  215. foreach ($rows as $row) {
  216. if (is_string($this->indexBy)) {
  217. $key = $row[$this->indexBy];
  218. } else {
  219. $key = call_user_func($this->indexBy, $row);
  220. }
  221. $result[$key] = $row;
  222. }
  223. return $result;
  224. }
  225. /**
  226. * Executes the query and returns a single row of result.
  227. * @param Connection $db the database connection used to generate the SQL statement.
  228. * If this parameter is not given, the `db` application component will be used.
  229. * @return array|boolean the first row (in terms of an array) of the query result. False is returned if the query
  230. * results in nothing.
  231. */
  232. public function one($db = null)
  233. {
  234. return $this->createCommand($db)->queryOne();
  235. }
  236. /**
  237. * Returns the query result as a scalar value.
  238. * The value returned will be the first column in the first row of the query results.
  239. * @param Connection $db the database connection used to generate the SQL statement.
  240. * If this parameter is not given, the `db` application component will be used.
  241. * @return string|null|false the value of the first column in the first row of the query result.
  242. * False is returned if the query result is empty.
  243. */
  244. public function scalar($db = null)
  245. {
  246. return $this->createCommand($db)->queryScalar();
  247. }
  248. /**
  249. * Executes the query and returns the first column of the result.
  250. * @param Connection $db the database connection used to generate the SQL statement.
  251. * If this parameter is not given, the `db` application component will be used.
  252. * @return array the first column of the query result. An empty array is returned if the query results in nothing.
  253. */
  254. public function column($db = null)
  255. {
  256. if ($this->indexBy === null) {
  257. return $this->createCommand($db)->queryColumn();
  258. }
  259. if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
  260. $this->select[] = $this->indexBy;
  261. }
  262. $rows = $this->createCommand($db)->queryAll();
  263. $results = [];
  264. foreach ($rows as $row) {
  265. $value = reset($row);
  266. if ($this->indexBy instanceof \Closure) {
  267. $results[call_user_func($this->indexBy, $row)] = $value;
  268. } else {
  269. $results[$row[$this->indexBy]] = $value;
  270. }
  271. }
  272. return $results;
  273. }
  274. /**
  275. * Returns the number of records.
  276. * @param string $q the COUNT expression. Defaults to '*'.
  277. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  278. * @param Connection $db the database connection used to generate the SQL statement.
  279. * If this parameter is not given (or null), the `db` application component will be used.
  280. * @return integer|string number of records. The result may be a string depending on the
  281. * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
  282. */
  283. public function count($q = '*', $db = null)
  284. {
  285. return $this->queryScalar("COUNT($q)", $db);
  286. }
  287. /**
  288. * Returns the sum of the specified column values.
  289. * @param string $q the column name or expression.
  290. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  291. * @param Connection $db the database connection used to generate the SQL statement.
  292. * If this parameter is not given, the `db` application component will be used.
  293. * @return mixed the sum of the specified column values.
  294. */
  295. public function sum($q, $db = null)
  296. {
  297. return $this->queryScalar("SUM($q)", $db);
  298. }
  299. /**
  300. * Returns the average of the specified column values.
  301. * @param string $q the column name or expression.
  302. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  303. * @param Connection $db the database connection used to generate the SQL statement.
  304. * If this parameter is not given, the `db` application component will be used.
  305. * @return mixed the average of the specified column values.
  306. */
  307. public function average($q, $db = null)
  308. {
  309. return $this->queryScalar("AVG($q)", $db);
  310. }
  311. /**
  312. * Returns the minimum of the specified column values.
  313. * @param string $q the column name or expression.
  314. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  315. * @param Connection $db the database connection used to generate the SQL statement.
  316. * If this parameter is not given, the `db` application component will be used.
  317. * @return mixed the minimum of the specified column values.
  318. */
  319. public function min($q, $db = null)
  320. {
  321. return $this->queryScalar("MIN($q)", $db);
  322. }
  323. /**
  324. * Returns the maximum of the specified column values.
  325. * @param string $q the column name or expression.
  326. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  327. * @param Connection $db the database connection used to generate the SQL statement.
  328. * If this parameter is not given, the `db` application component will be used.
  329. * @return mixed the maximum of the specified column values.
  330. */
  331. public function max($q, $db = null)
  332. {
  333. return $this->queryScalar("MAX($q)", $db);
  334. }
  335. /**
  336. * Returns a value indicating whether the query result contains any row of data.
  337. * @param Connection $db the database connection used to generate the SQL statement.
  338. * If this parameter is not given, the `db` application component will be used.
  339. * @return boolean whether the query result contains any row of data.
  340. */
  341. public function exists($db = null)
  342. {
  343. $command = $this->createCommand($db);
  344. $params = $command->params;
  345. $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
  346. $command->bindValues($params);
  347. return (boolean)$command->queryScalar();
  348. }
  349. /**
  350. * Queries a scalar value by setting [[select]] first.
  351. * Restores the value of select to make this query reusable.
  352. * @param string|Expression $selectExpression
  353. * @param Connection|null $db
  354. * @return boolean|string
  355. */
  356. protected function queryScalar($selectExpression, $db)
  357. {
  358. $select = $this->select;
  359. $limit = $this->limit;
  360. $offset = $this->offset;
  361. $this->select = [$selectExpression];
  362. $this->limit = null;
  363. $this->offset = null;
  364. $command = $this->createCommand($db);
  365. $this->select = $select;
  366. $this->limit = $limit;
  367. $this->offset = $offset;
  368. if (empty($this->groupBy) && empty($this->having) && empty($this->union) && !$this->distinct) {
  369. return $command->queryScalar();
  370. } else {
  371. return (new Query)->select([$selectExpression])
  372. ->from(['c' => $this])
  373. ->createCommand($command->db)
  374. ->queryScalar();
  375. }
  376. }
  377. /**
  378. * Sets the SELECT part of the query.
  379. * @param string|array|Expression $columns the columns to be selected.
  380. * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
  381. * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
  382. * The method will automatically quote the column names unless a column contains some parenthesis
  383. * (which means the column contains a DB expression). A DB expression may also be passed in form of
  384. * an [[Expression]] object.
  385. *
  386. * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
  387. * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
  388. *
  389. * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
  390. * does not need alias, do not use a string key).
  391. *
  392. * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
  393. * as a `Query` instance representing the sub-query.
  394. *
  395. * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
  396. * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
  397. * @return $this the query object itself
  398. */
  399. public function select($columns, $option = null)
  400. {
  401. if ($columns instanceof Expression) {
  402. $columns = [$columns];
  403. } elseif (!is_array($columns)) {
  404. $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
  405. }
  406. $this->select = $columns;
  407. $this->selectOption = $option;
  408. return $this;
  409. }
  410. /**
  411. * Add more columns to the SELECT part of the query.
  412. *
  413. * Note, that if [[select]] has not been specified before, you should include `*` explicitly
  414. * if you want to select all remaining columns too:
  415. *
  416. * ```php
  417. * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
  418. * ```
  419. *
  420. * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
  421. * details about the format of this parameter.
  422. * @return $this the query object itself
  423. * @see select()
  424. */
  425. public function addSelect($columns)
  426. {
  427. if ($columns instanceof Expression) {
  428. $columns = [$columns];
  429. } elseif (!is_array($columns)) {
  430. $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
  431. }
  432. if ($this->select === null) {
  433. $this->select = $columns;
  434. } else {
  435. $this->select = array_merge($this->select, $columns);
  436. }
  437. return $this;
  438. }
  439. /**
  440. * Sets the value indicating whether to SELECT DISTINCT or not.
  441. * @param boolean $value whether to SELECT DISTINCT or not.
  442. * @return $this the query object itself
  443. */
  444. public function distinct($value = true)
  445. {
  446. $this->distinct = $value;
  447. return $this;
  448. }
  449. /**
  450. * Sets the FROM part of the query.
  451. * @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
  452. * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
  453. * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
  454. * The method will automatically quote the table names unless it contains some parenthesis
  455. * (which means the table is given as a sub-query or DB expression).
  456. *
  457. * When the tables are specified as an array, you may also use the array keys as the table aliases
  458. * (if a table does not need alias, do not use a string key).
  459. *
  460. * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
  461. * as the alias for the sub-query.
  462. *
  463. * Here are some examples:
  464. *
  465. * ```php
  466. * // SELECT * FROM `user` `u`, `profile`;
  467. * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
  468. *
  469. * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
  470. * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
  471. * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
  472. *
  473. * // subquery can also be a string with plain SQL wrapped in parenthesis
  474. * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
  475. * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
  476. * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
  477. * ```
  478. *
  479. * @return $this the query object itself
  480. */
  481. public function from($tables)
  482. {
  483. if (!is_array($tables)) {
  484. $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
  485. }
  486. $this->from = $tables;
  487. return $this;
  488. }
  489. /**
  490. * Sets the WHERE part of the query.
  491. *
  492. * The method requires a `$condition` parameter, and optionally a `$params` parameter
  493. * specifying the values to be bound to the query.
  494. *
  495. * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
  496. *
  497. * @inheritdoc
  498. *
  499. * @param string|array|Expression $condition the conditions that should be put in the WHERE part.
  500. * @param array $params the parameters (name => value) to be bound to the query.
  501. * @return $this the query object itself
  502. * @see andWhere()
  503. * @see orWhere()
  504. * @see QueryInterface::where()
  505. */
  506. public function where($condition, $params = [])
  507. {
  508. $this->where = $condition;
  509. $this->addParams($params);
  510. return $this;
  511. }
  512. /**
  513. * Adds an additional WHERE condition to the existing one.
  514. * The new condition and the existing one will be joined using the 'AND' operator.
  515. * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
  516. * on how to specify this parameter.
  517. * @param array $params the parameters (name => value) to be bound to the query.
  518. * @return $this the query object itself
  519. * @see where()
  520. * @see orWhere()
  521. */
  522. public function andWhere($condition, $params = [])
  523. {
  524. if ($this->where === null) {
  525. $this->where = $condition;
  526. } else {
  527. $this->where = ['and', $this->where, $condition];
  528. }
  529. $this->addParams($params);
  530. return $this;
  531. }
  532. /**
  533. * Adds an additional WHERE condition to the existing one.
  534. * The new condition and the existing one will be joined using the 'OR' operator.
  535. * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
  536. * on how to specify this parameter.
  537. * @param array $params the parameters (name => value) to be bound to the query.
  538. * @return $this the query object itself
  539. * @see where()
  540. * @see andWhere()
  541. */
  542. public function orWhere($condition, $params = [])
  543. {
  544. if ($this->where === null) {
  545. $this->where = $condition;
  546. } else {
  547. $this->where = ['or', $this->where, $condition];
  548. }
  549. $this->addParams($params);
  550. return $this;
  551. }
  552. /**
  553. * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
  554. *
  555. * It adds an additional WHERE condition for the given field and determines the comparison operator
  556. * based on the first few characters of the given value.
  557. * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
  558. * The new condition and the existing one will be joined using the 'AND' operator.
  559. *
  560. * The comparison operator is intelligently determined based on the first few characters in the given value.
  561. * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
  562. *
  563. * - `<`: the column must be less than the given value.
  564. * - `>`: the column must be greater than the given value.
  565. * - `<=`: the column must be less than or equal to the given value.
  566. * - `>=`: the column must be greater than or equal to the given value.
  567. * - `<>`: the column must not be the same as the given value.
  568. * - `=`: the column must be equal to the given value.
  569. * - If none of the above operators is detected, the `$defaultOperator` will be used.
  570. *
  571. * @param string $name the column name.
  572. * @param string $value the column value optionally prepended with the comparison operator.
  573. * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
  574. * Defaults to `=`, performing an exact match.
  575. * @return $this The query object itself
  576. * @since 2.0.8
  577. */
  578. public function andFilterCompare($name, $value, $defaultOperator = '=')
  579. {
  580. if (preg_match('/^(<>|>=|>|<=|<|=)/', $value, $matches)) {
  581. $operator = $matches[1];
  582. $value = substr($value, strlen($operator));
  583. } else {
  584. $operator = $defaultOperator;
  585. }
  586. return $this->andFilterWhere([$operator, $name, $value]);
  587. }
  588. /**
  589. * Appends a JOIN part to the query.
  590. * The first parameter specifies what type of join it is.
  591. * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
  592. * @param string|array $table the table to be joined.
  593. *
  594. * Use a string to represent the name of the table to be joined.
  595. * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
  596. * The method will automatically quote the table name unless it contains some parenthesis
  597. * (which means the table is given as a sub-query or DB expression).
  598. *
  599. * Use an array to represent joining with a sub-query. The array must contain only one element.
  600. * The value must be a [[Query]] object representing the sub-query while the corresponding key
  601. * represents the alias for the sub-query.
  602. *
  603. * @param string|array $on the join condition that should appear in the ON part.
  604. * Please refer to [[where()]] on how to specify this parameter.
  605. *
  606. * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
  607. * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
  608. * match the `post.author_id` column value against the string `'user.id'`.
  609. * It is recommended to use the string syntax here which is more suited for a join:
  610. *
  611. * ```php
  612. * 'post.author_id = user.id'
  613. * ```
  614. *
  615. * @param array $params the parameters (name => value) to be bound to the query.
  616. * @return $this the query object itself
  617. */
  618. public function join($type, $table, $on = '', $params = [])
  619. {
  620. $this->join[] = [$type, $table, $on];
  621. return $this->addParams($params);
  622. }
  623. /**
  624. * Appends an INNER JOIN part to the query.
  625. * @param string|array $table the table to be joined.
  626. *
  627. * Use a string to represent the name of the table to be joined.
  628. * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
  629. * The method will automatically quote the table name unless it contains some parenthesis
  630. * (which means the table is given as a sub-query or DB expression).
  631. *
  632. * Use an array to represent joining with a sub-query. The array must contain only one element.
  633. * The value must be a [[Query]] object representing the sub-query while the corresponding key
  634. * represents the alias for the sub-query.
  635. *
  636. * @param string|array $on the join condition that should appear in the ON part.
  637. * Please refer to [[join()]] on how to specify this parameter.
  638. * @param array $params the parameters (name => value) to be bound to the query.
  639. * @return $this the query object itself
  640. */
  641. public function innerJoin($table, $on = '', $params = [])
  642. {
  643. $this->join[] = ['INNER JOIN', $table, $on];
  644. return $this->addParams($params);
  645. }
  646. /**
  647. * Appends a LEFT OUTER JOIN part to the query.
  648. * @param string|array $table the table to be joined.
  649. *
  650. * Use a string to represent the name of the table to be joined.
  651. * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
  652. * The method will automatically quote the table name unless it contains some parenthesis
  653. * (which means the table is given as a sub-query or DB expression).
  654. *
  655. * Use an array to represent joining with a sub-query. The array must contain only one element.
  656. * The value must be a [[Query]] object representing the sub-query while the corresponding key
  657. * represents the alias for the sub-query.
  658. *
  659. * @param string|array $on the join condition that should appear in the ON part.
  660. * Please refer to [[join()]] on how to specify this parameter.
  661. * @param array $params the parameters (name => value) to be bound to the query
  662. * @return $this the query object itself
  663. */
  664. public function leftJoin($table, $on = '', $params = [])
  665. {
  666. $this->join[] = ['LEFT JOIN', $table, $on];
  667. return $this->addParams($params);
  668. }
  669. /**
  670. * Appends a RIGHT OUTER JOIN part to the query.
  671. * @param string|array $table the table to be joined.
  672. *
  673. * Use a string to represent the name of the table to be joined.
  674. * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
  675. * The method will automatically quote the table name unless it contains some parenthesis
  676. * (which means the table is given as a sub-query or DB expression).
  677. *
  678. * Use an array to represent joining with a sub-query. The array must contain only one element.
  679. * The value must be a [[Query]] object representing the sub-query while the corresponding key
  680. * represents the alias for the sub-query.
  681. *
  682. * @param string|array $on the join condition that should appear in the ON part.
  683. * Please refer to [[join()]] on how to specify this parameter.
  684. * @param array $params the parameters (name => value) to be bound to the query
  685. * @return $this the query object itself
  686. */
  687. public function rightJoin($table, $on = '', $params = [])
  688. {
  689. $this->join[] = ['RIGHT JOIN', $table, $on];
  690. return $this->addParams($params);
  691. }
  692. /**
  693. * Sets the GROUP BY part of the query.
  694. * @param string|array|Expression $columns the columns to be grouped by.
  695. * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
  696. * The method will automatically quote the column names unless a column contains some parenthesis
  697. * (which means the column contains a DB expression).
  698. *
  699. * Note that if your group-by is an expression containing commas, you should always use an array
  700. * to represent the group-by information. Otherwise, the method will not be able to correctly determine
  701. * the group-by columns.
  702. *
  703. * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
  704. * @return $this the query object itself
  705. * @see addGroupBy()
  706. */
  707. public function groupBy($columns)
  708. {
  709. if ($columns instanceof Expression) {
  710. $columns = [$columns];
  711. } elseif (!is_array($columns)) {
  712. $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
  713. }
  714. $this->groupBy = $columns;
  715. return $this;
  716. }
  717. /**
  718. * Adds additional group-by columns to the existing ones.
  719. * @param string|array $columns additional columns to be grouped by.
  720. * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
  721. * The method will automatically quote the column names unless a column contains some parenthesis
  722. * (which means the column contains a DB expression).
  723. *
  724. * Note that if your group-by is an expression containing commas, you should always use an array
  725. * to represent the group-by information. Otherwise, the method will not be able to correctly determine
  726. * the group-by columns.
  727. *
  728. * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
  729. * @return $this the query object itself
  730. * @see groupBy()
  731. */
  732. public function addGroupBy($columns)
  733. {
  734. if ($columns instanceof Expression) {
  735. $columns = [$columns];
  736. } elseif (!is_array($columns)) {
  737. $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
  738. }
  739. if ($this->groupBy === null) {
  740. $this->groupBy = $columns;
  741. } else {
  742. $this->groupBy = array_merge($this->groupBy, $columns);
  743. }
  744. return $this;
  745. }
  746. /**
  747. * Sets the HAVING part of the query.
  748. * @param string|array|Expression $condition the conditions to be put after HAVING.
  749. * Please refer to [[where()]] on how to specify this parameter.
  750. * @param array $params the parameters (name => value) to be bound to the query.
  751. * @return $this the query object itself
  752. * @see andHaving()
  753. * @see orHaving()
  754. */
  755. public function having($condition, $params = [])
  756. {
  757. $this->having = $condition;
  758. $this->addParams($params);
  759. return $this;
  760. }
  761. /**
  762. * Adds an additional HAVING condition to the existing one.
  763. * The new condition and the existing one will be joined using the 'AND' operator.
  764. * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
  765. * on how to specify this parameter.
  766. * @param array $params the parameters (name => value) to be bound to the query.
  767. * @return $this the query object itself
  768. * @see having()
  769. * @see orHaving()
  770. */
  771. public function andHaving($condition, $params = [])
  772. {
  773. if ($this->having === null) {
  774. $this->having = $condition;
  775. } else {
  776. $this->having = ['and', $this->having, $condition];
  777. }
  778. $this->addParams($params);
  779. return $this;
  780. }
  781. /**
  782. * Adds an additional HAVING condition to the existing one.
  783. * The new condition and the existing one will be joined using the 'OR' operator.
  784. * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
  785. * on how to specify this parameter.
  786. * @param array $params the parameters (name => value) to be bound to the query.
  787. * @return $this the query object itself
  788. * @see having()
  789. * @see andHaving()
  790. */
  791. public function orHaving($condition, $params = [])
  792. {
  793. if ($this->having === null) {
  794. $this->having = $condition;
  795. } else {
  796. $this->having = ['or', $this->having, $condition];
  797. }
  798. $this->addParams($params);
  799. return $this;
  800. }
  801. /**
  802. * Appends a SQL statement using UNION operator.
  803. * @param string|Query $sql the SQL statement to be appended using UNION
  804. * @param boolean $all TRUE if using UNION ALL and FALSE if using UNION
  805. * @return $this the query object itself
  806. */
  807. public function union($sql, $all = false)
  808. {
  809. $this->union[] = ['query' => $sql, 'all' => $all];
  810. return $this;
  811. }
  812. /**
  813. * Sets the parameters to be bound to the query.
  814. * @param array $params list of query parameter values indexed by parameter placeholders.
  815. * For example, `[':name' => 'Dan', ':age' => 31]`.
  816. * @return $this the query object itself
  817. * @see addParams()
  818. */
  819. public function params($params)
  820. {
  821. $this->params = $params;
  822. return $this;
  823. }
  824. /**
  825. * Adds additional parameters to be bound to the query.
  826. * @param array $params list of query parameter values indexed by parameter placeholders.
  827. * For example, `[':name' => 'Dan', ':age' => 31]`.
  828. * @return $this the query object itself
  829. * @see params()
  830. */
  831. public function addParams($params)
  832. {
  833. if (!empty($params)) {
  834. if (empty($this->params)) {
  835. $this->params = $params;
  836. } else {
  837. foreach ($params as $name => $value) {
  838. if (is_int($name)) {
  839. $this->params[] = $value;
  840. } else {
  841. $this->params[$name] = $value;
  842. }
  843. }
  844. }
  845. }
  846. return $this;
  847. }
  848. /**
  849. * Creates a new Query object and copies its property values from an existing one.
  850. * The properties being copies are the ones to be used by query builders.
  851. * @param Query $from the source query object
  852. * @return Query the new Query object
  853. */
  854. public static function create($from)
  855. {
  856. return new self([
  857. 'where' => $from->where,
  858. 'limit' => $from->limit,
  859. 'offset' => $from->offset,
  860. 'orderBy' => $from->orderBy,
  861. 'indexBy' => $from->indexBy,
  862. 'select' => $from->select,
  863. 'selectOption' => $from->selectOption,
  864. 'distinct' => $from->distinct,
  865. 'from' => $from->from,
  866. 'groupBy' => $from->groupBy,
  867. 'join' => $from->join,
  868. 'having' => $from->having,
  869. 'union' => $from->union,
  870. 'params' => $from->params,
  871. ]);
  872. }
  873. }