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.

807 lines
30KB

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