No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

919 líneas
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 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 10 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 (!is_string($this->indexBy)) {
  257. return $this->createCommand($db)->queryColumn();
  258. }
  259. if (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. if (array_key_exists($this->indexBy, $row)) {
  266. $results[$row[$this->indexBy]] = reset($row);
  267. } else {
  268. $results[] = reset($row);
  269. }
  270. }
  271. return $results;
  272. }
  273. /**
  274. * Returns the number of records.
  275. * @param string $q the COUNT expression. Defaults to '*'.
  276. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  277. * @param Connection $db the database connection used to generate the SQL statement.
  278. * If this parameter is not given (or null), the `db` application component will be used.
  279. * @return integer|string number of records. The result may be a string depending on the
  280. * underlying database engine and to support integer values higher than a 32bit PHP integer can handle.
  281. */
  282. public function count($q = '*', $db = null)
  283. {
  284. return $this->queryScalar("COUNT($q)", $db);
  285. }
  286. /**
  287. * Returns the sum of the specified column values.
  288. * @param string $q the column name or expression.
  289. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  290. * @param Connection $db the database connection used to generate the SQL statement.
  291. * If this parameter is not given, the `db` application component will be used.
  292. * @return mixed the sum of the specified column values.
  293. */
  294. public function sum($q, $db = null)
  295. {
  296. return $this->queryScalar("SUM($q)", $db);
  297. }
  298. /**
  299. * Returns the average of the specified column values.
  300. * @param string $q the column name or expression.
  301. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  302. * @param Connection $db the database connection used to generate the SQL statement.
  303. * If this parameter is not given, the `db` application component will be used.
  304. * @return mixed the average of the specified column values.
  305. */
  306. public function average($q, $db = null)
  307. {
  308. return $this->queryScalar("AVG($q)", $db);
  309. }
  310. /**
  311. * Returns the minimum of the specified column values.
  312. * @param string $q the column name or expression.
  313. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  314. * @param Connection $db the database connection used to generate the SQL statement.
  315. * If this parameter is not given, the `db` application component will be used.
  316. * @return mixed the minimum of the specified column values.
  317. */
  318. public function min($q, $db = null)
  319. {
  320. return $this->queryScalar("MIN($q)", $db);
  321. }
  322. /**
  323. * Returns the maximum of the specified column values.
  324. * @param string $q the column name or expression.
  325. * Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
  326. * @param Connection $db the database connection used to generate the SQL statement.
  327. * If this parameter is not given, the `db` application component will be used.
  328. * @return mixed the maximum of the specified column values.
  329. */
  330. public function max($q, $db = null)
  331. {
  332. return $this->queryScalar("MAX($q)", $db);
  333. }
  334. /**
  335. * Returns a value indicating whether the query result contains any row of data.
  336. * @param Connection $db the database connection used to generate the SQL statement.
  337. * If this parameter is not given, the `db` application component will be used.
  338. * @return boolean whether the query result contains any row of data.
  339. */
  340. public function exists($db = null)
  341. {
  342. $command = $this->createCommand($db);
  343. $params = $command->params;
  344. $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
  345. $command->bindValues($params);
  346. return (boolean)$command->queryScalar();
  347. }
  348. /**
  349. * Queries a scalar value by setting [[select]] first.
  350. * Restores the value of select to make this query reusable.
  351. * @param string|Expression $selectExpression
  352. * @param Connection|null $db
  353. * @return boolean|string
  354. */
  355. protected function queryScalar($selectExpression, $db)
  356. {
  357. $select = $this->select;
  358. $limit = $this->limit;
  359. $offset = $this->offset;
  360. $this->select = [$selectExpression];
  361. $this->limit = null;
  362. $this->offset = null;
  363. $command = $this->createCommand($db);
  364. $this->select = $select;
  365. $this->limit = $limit;
  366. $this->offset = $offset;
  367. if (empty($this->groupBy) && empty($this->having) && empty($this->union) && !$this->distinct) {
  368. return $command->queryScalar();
  369. } else {
  370. return (new Query)->select([$selectExpression])
  371. ->from(['c' => $this])
  372. ->createCommand($command->db)
  373. ->queryScalar();
  374. }
  375. }
  376. /**
  377. * Sets the SELECT part of the query.
  378. * @param string|array|Expression $columns the columns to be selected.
  379. * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
  380. * Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
  381. * The method will automatically quote the column names unless a column contains some parenthesis
  382. * (which means the column contains a DB expression). A DB expression may also be passed in form of
  383. * an [[Expression]] object.
  384. *
  385. * Note that if you are selecting an expression like `CONCAT(first_name, ' ', last_name)`, you should
  386. * use an array to specify the columns. Otherwise, the expression may be incorrectly split into several parts.
  387. *
  388. * When the columns are specified as an array, you may also use array keys as the column aliases (if a column
  389. * does not need alias, do not use a string key).
  390. *
  391. * Starting from version 2.0.1, you may also select sub-queries as columns by specifying each such column
  392. * as a `Query` instance representing the sub-query.
  393. *
  394. * @param string $option additional option that should be appended to the 'SELECT' keyword. For example,
  395. * in MySQL, the option 'SQL_CALC_FOUND_ROWS' can be used.
  396. * @return $this the query object itself
  397. */
  398. public function select($columns, $option = null)
  399. {
  400. if ($columns instanceof Expression) {
  401. $columns = [$columns];
  402. } elseif (!is_array($columns)) {
  403. $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
  404. }
  405. $this->select = $columns;
  406. $this->selectOption = $option;
  407. return $this;
  408. }
  409. /**
  410. * Add more columns to the SELECT part of the query.
  411. *
  412. * Note, that if [[select]] has not been specified before, you should include `*` explicitly
  413. * if you want to select all remaining columns too:
  414. *
  415. * ```php
  416. * $query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();
  417. * ```
  418. *
  419. * @param string|array|Expression $columns the columns to add to the select. See [[select()]] for more
  420. * details about the format of this parameter.
  421. * @return $this the query object itself
  422. * @see select()
  423. */
  424. public function addSelect($columns)
  425. {
  426. if ($columns instanceof Expression) {
  427. $columns = [$columns];
  428. } elseif (!is_array($columns)) {
  429. $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
  430. }
  431. if ($this->select === null) {
  432. $this->select = $columns;
  433. } else {
  434. $this->select = array_merge($this->select, $columns);
  435. }
  436. return $this;
  437. }
  438. /**
  439. * Sets the value indicating whether to SELECT DISTINCT or not.
  440. * @param boolean $value whether to SELECT DISTINCT or not.
  441. * @return $this the query object itself
  442. */
  443. public function distinct($value = true)
  444. {
  445. $this->distinct = $value;
  446. return $this;
  447. }
  448. /**
  449. * Sets the FROM part of the query.
  450. * @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
  451. * or an array (e.g. `['user', 'profile']`) specifying one or several table names.
  452. * Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
  453. * The method will automatically quote the table names unless it contains some parenthesis
  454. * (which means the table is given as a sub-query or DB expression).
  455. *
  456. * When the tables are specified as an array, you may also use the array keys as the table aliases
  457. * (if a table does not need alias, do not use a string key).
  458. *
  459. * Use a Query object to represent a sub-query. In this case, the corresponding array key will be used
  460. * as the alias for the sub-query.
  461. *
  462. * Here are some examples:
  463. *
  464. * ```php
  465. * // SELECT * FROM `user` `u`, `profile`;
  466. * $query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);
  467. *
  468. * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
  469. * $subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
  470. * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
  471. *
  472. * // subquery can also be a string with plain SQL wrapped in parenthesis
  473. * // SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
  474. * $subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
  475. * $query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
  476. * ```
  477. *
  478. * @return $this the query object itself
  479. */
  480. public function from($tables)
  481. {
  482. if (!is_array($tables)) {
  483. $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
  484. }
  485. $this->from = $tables;
  486. return $this;
  487. }
  488. /**
  489. * Sets the WHERE part of the query.
  490. *
  491. * The method requires a `$condition` parameter, and optionally a `$params` parameter
  492. * specifying the values to be bound to the query.
  493. *
  494. * The `$condition` parameter should be either a string (e.g. `'id=1'`) or an array.
  495. *
  496. * @inheritdoc
  497. *
  498. * @param string|array|Expression $condition the conditions that should be put in the WHERE part.
  499. * @param array $params the parameters (name => value) to be bound to the query.
  500. * @return $this the query object itself
  501. * @see andWhere()
  502. * @see orWhere()
  503. * @see QueryInterface::where()
  504. */
  505. public function where($condition, $params = [])
  506. {
  507. $this->where = $condition;
  508. $this->addParams($params);
  509. return $this;
  510. }
  511. /**
  512. * Adds an additional WHERE condition to the existing one.
  513. * The new condition and the existing one will be joined using the 'AND' operator.
  514. * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
  515. * on how to specify this parameter.
  516. * @param array $params the parameters (name => value) to be bound to the query.
  517. * @return $this the query object itself
  518. * @see where()
  519. * @see orWhere()
  520. */
  521. public function andWhere($condition, $params = [])
  522. {
  523. if ($this->where === null) {
  524. $this->where = $condition;
  525. } else {
  526. $this->where = ['and', $this->where, $condition];
  527. }
  528. $this->addParams($params);
  529. return $this;
  530. }
  531. /**
  532. * Adds an additional WHERE condition to the existing one.
  533. * The new condition and the existing one will be joined using the 'OR' operator.
  534. * @param string|array|Expression $condition the new WHERE condition. Please refer to [[where()]]
  535. * on how to specify this parameter.
  536. * @param array $params the parameters (name => value) to be bound to the query.
  537. * @return $this the query object itself
  538. * @see where()
  539. * @see andWhere()
  540. */
  541. public function orWhere($condition, $params = [])
  542. {
  543. if ($this->where === null) {
  544. $this->where = $condition;
  545. } else {
  546. $this->where = ['or', $this->where, $condition];
  547. }
  548. $this->addParams($params);
  549. return $this;
  550. }
  551. /**
  552. * Adds a filtering condition for a specific column and allow the user to choose a filter operator.
  553. *
  554. * It adds an additional WHERE condition for the given field and determines the comparison operator
  555. * based on the first few characters of the given value.
  556. * The condition is added in the same way as in [[andFilterWhere]] so [[isEmpty()|empty values]] are ignored.
  557. * The new condition and the existing one will be joined using the 'AND' operator.
  558. *
  559. * The comparison operator is intelligently determined based on the first few characters in the given value.
  560. * In particular, it recognizes the following operators if they appear as the leading characters in the given value:
  561. *
  562. * - `<`: the column must be less than the given value.
  563. * - `>`: the column must be greater than the given value.
  564. * - `<=`: the column must be less than or equal to the given value.
  565. * - `>=`: the column must be greater than or equal to the given value.
  566. * - `<>`: the column must not be the same as the given value.
  567. * - `=`: the column must be equal to the given value.
  568. * - If none of the above operators is detected, the `$defaultOperator` will be used.
  569. *
  570. * @param string $name the column name.
  571. * @param string $value the column value optionally prepended with the comparison operator.
  572. * @param string $defaultOperator The operator to use, when no operator is given in `$value`.
  573. * Defaults to `=`, performing an exact match.
  574. * @return $this The query object itself
  575. * @since 2.0.8
  576. */
  577. public function andFilterCompare($name, $value, $defaultOperator = '=')
  578. {
  579. if (preg_match("/^(<>|>=|>|<=|<|=)/", $value, $matches)) {
  580. $operator = $matches[1];
  581. $value = substr($value, strlen($operator));
  582. } else {
  583. $operator = $defaultOperator;
  584. }
  585. return $this->andFilterWhere([$operator, $name, $value]);
  586. }
  587. /**
  588. * Appends a JOIN part to the query.
  589. * The first parameter specifies what type of join it is.
  590. * @param string $type the type of join, such as INNER JOIN, LEFT JOIN.
  591. * @param string|array $table the table to be joined.
  592. *
  593. * Use a string to represent the name of the table to be joined.
  594. * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
  595. * The method will automatically quote the table name unless it contains some parenthesis
  596. * (which means the table is given as a sub-query or DB expression).
  597. *
  598. * Use an array to represent joining with a sub-query. The array must contain only one element.
  599. * The value must be a [[Query]] object representing the sub-query while the corresponding key
  600. * represents the alias for the sub-query.
  601. *
  602. * @param string|array $on the join condition that should appear in the ON part.
  603. * Please refer to [[where()]] on how to specify this parameter.
  604. *
  605. * Note that the array format of [[where()]] is designed to match columns to values instead of columns to columns, so
  606. * the following would **not** work as expected: `['post.author_id' => 'user.id']`, it would
  607. * match the `post.author_id` column value against the string `'user.id'`.
  608. * It is recommended to use the string syntax here which is more suited for a join:
  609. *
  610. * ```php
  611. * 'post.author_id = user.id'
  612. * ```
  613. *
  614. * @param array $params the parameters (name => value) to be bound to the query.
  615. * @return $this the query object itself
  616. */
  617. public function join($type, $table, $on = '', $params = [])
  618. {
  619. $this->join[] = [$type, $table, $on];
  620. return $this->addParams($params);
  621. }
  622. /**
  623. * Appends an INNER JOIN part to the query.
  624. * @param string|array $table the table to be joined.
  625. *
  626. * Use a string to represent the name of the table to be joined.
  627. * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
  628. * The method will automatically quote the table name unless it contains some parenthesis
  629. * (which means the table is given as a sub-query or DB expression).
  630. *
  631. * Use an array to represent joining with a sub-query. The array must contain only one element.
  632. * The value must be a [[Query]] object representing the sub-query while the corresponding key
  633. * represents the alias for the sub-query.
  634. *
  635. * @param string|array $on the join condition that should appear in the ON part.
  636. * Please refer to [[join()]] on how to specify this parameter.
  637. * @param array $params the parameters (name => value) to be bound to the query.
  638. * @return $this the query object itself
  639. */
  640. public function innerJoin($table, $on = '', $params = [])
  641. {
  642. $this->join[] = ['INNER JOIN', $table, $on];
  643. return $this->addParams($params);
  644. }
  645. /**
  646. * Appends a LEFT OUTER JOIN part to the query.
  647. * @param string|array $table the table to be joined.
  648. *
  649. * Use a string to represent the name of the table to be joined.
  650. * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
  651. * The method will automatically quote the table name unless it contains some parenthesis
  652. * (which means the table is given as a sub-query or DB expression).
  653. *
  654. * Use an array to represent joining with a sub-query. The array must contain only one element.
  655. * The value must be a [[Query]] object representing the sub-query while the corresponding key
  656. * represents the alias for the sub-query.
  657. *
  658. * @param string|array $on the join condition that should appear in the ON part.
  659. * Please refer to [[join()]] on how to specify this parameter.
  660. * @param array $params the parameters (name => value) to be bound to the query
  661. * @return $this the query object itself
  662. */
  663. public function leftJoin($table, $on = '', $params = [])
  664. {
  665. $this->join[] = ['LEFT JOIN', $table, $on];
  666. return $this->addParams($params);
  667. }
  668. /**
  669. * Appends a RIGHT OUTER JOIN part to the query.
  670. * @param string|array $table the table to be joined.
  671. *
  672. * Use a string to represent the name of the table to be joined.
  673. * The table name can contain a schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
  674. * The method will automatically quote the table name unless it contains some parenthesis
  675. * (which means the table is given as a sub-query or DB expression).
  676. *
  677. * Use an array to represent joining with a sub-query. The array must contain only one element.
  678. * The value must be a [[Query]] object representing the sub-query while the corresponding key
  679. * represents the alias for the sub-query.
  680. *
  681. * @param string|array $on the join condition that should appear in the ON part.
  682. * Please refer to [[join()]] on how to specify this parameter.
  683. * @param array $params the parameters (name => value) to be bound to the query
  684. * @return $this the query object itself
  685. */
  686. public function rightJoin($table, $on = '', $params = [])
  687. {
  688. $this->join[] = ['RIGHT JOIN', $table, $on];
  689. return $this->addParams($params);
  690. }
  691. /**
  692. * Sets the GROUP BY part of the query.
  693. * @param string|array|Expression $columns the columns to be grouped by.
  694. * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
  695. * The method will automatically quote the column names unless a column contains some parenthesis
  696. * (which means the column contains a DB expression).
  697. *
  698. * Note that if your group-by is an expression containing commas, you should always use an array
  699. * to represent the group-by information. Otherwise, the method will not be able to correctly determine
  700. * the group-by columns.
  701. *
  702. * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
  703. * @return $this the query object itself
  704. * @see addGroupBy()
  705. */
  706. public function groupBy($columns)
  707. {
  708. if ($columns instanceof Expression) {
  709. $columns = [$columns];
  710. } elseif (!is_array($columns)) {
  711. $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
  712. }
  713. $this->groupBy = $columns;
  714. return $this;
  715. }
  716. /**
  717. * Adds additional group-by columns to the existing ones.
  718. * @param string|array $columns additional columns to be grouped by.
  719. * Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
  720. * The method will automatically quote the column names unless a column contains some parenthesis
  721. * (which means the column contains a DB expression).
  722. *
  723. * Note that if your group-by is an expression containing commas, you should always use an array
  724. * to represent the group-by information. Otherwise, the method will not be able to correctly determine
  725. * the group-by columns.
  726. *
  727. * Since version 2.0.7, an [[Expression]] object can be passed to specify the GROUP BY part explicitly in plain SQL.
  728. * @return $this the query object itself
  729. * @see groupBy()
  730. */
  731. public function addGroupBy($columns)
  732. {
  733. if ($columns instanceof Expression) {
  734. $columns = [$columns];
  735. } elseif (!is_array($columns)) {
  736. $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
  737. }
  738. if ($this->groupBy === null) {
  739. $this->groupBy = $columns;
  740. } else {
  741. $this->groupBy = array_merge($this->groupBy, $columns);
  742. }
  743. return $this;
  744. }
  745. /**
  746. * Sets the HAVING part of the query.
  747. * @param string|array|Expression $condition the conditions to be put after HAVING.
  748. * Please refer to [[where()]] on how to specify this parameter.
  749. * @param array $params the parameters (name => value) to be bound to the query.
  750. * @return $this the query object itself
  751. * @see andHaving()
  752. * @see orHaving()
  753. */
  754. public function having($condition, $params = [])
  755. {
  756. $this->having = $condition;
  757. $this->addParams($params);
  758. return $this;
  759. }
  760. /**
  761. * Adds an additional HAVING condition to the existing one.
  762. * The new condition and the existing one will be joined using the 'AND' operator.
  763. * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
  764. * on how to specify this parameter.
  765. * @param array $params the parameters (name => value) to be bound to the query.
  766. * @return $this the query object itself
  767. * @see having()
  768. * @see orHaving()
  769. */
  770. public function andHaving($condition, $params = [])
  771. {
  772. if ($this->having === null) {
  773. $this->having = $condition;
  774. } else {
  775. $this->having = ['and', $this->having, $condition];
  776. }
  777. $this->addParams($params);
  778. return $this;
  779. }
  780. /**
  781. * Adds an additional HAVING condition to the existing one.
  782. * The new condition and the existing one will be joined using the 'OR' operator.
  783. * @param string|array|Expression $condition the new HAVING condition. Please refer to [[where()]]
  784. * on how to specify this parameter.
  785. * @param array $params the parameters (name => value) to be bound to the query.
  786. * @return $this the query object itself
  787. * @see having()
  788. * @see andHaving()
  789. */
  790. public function orHaving($condition, $params = [])
  791. {
  792. if ($this->having === null) {
  793. $this->having = $condition;
  794. } else {
  795. $this->having = ['or', $this->having, $condition];
  796. }
  797. $this->addParams($params);
  798. return $this;
  799. }
  800. /**
  801. * Appends a SQL statement using UNION operator.
  802. * @param string|Query $sql the SQL statement to be appended using UNION
  803. * @param boolean $all TRUE if using UNION ALL and FALSE if using UNION
  804. * @return $this the query object itself
  805. */
  806. public function union($sql, $all = false)
  807. {
  808. $this->union[] = ['query' => $sql, 'all' => $all];
  809. return $this;
  810. }
  811. /**
  812. * Sets the parameters to be bound to the query.
  813. * @param array $params list of query parameter values indexed by parameter placeholders.
  814. * For example, `[':name' => 'Dan', ':age' => 31]`.
  815. * @return $this the query object itself
  816. * @see addParams()
  817. */
  818. public function params($params)
  819. {
  820. $this->params = $params;
  821. return $this;
  822. }
  823. /**
  824. * Adds additional parameters to be bound to the query.
  825. * @param array $params list of query parameter values indexed by parameter placeholders.
  826. * For example, `[':name' => 'Dan', ':age' => 31]`.
  827. * @return $this the query object itself
  828. * @see params()
  829. */
  830. public function addParams($params)
  831. {
  832. if (!empty($params)) {
  833. if (empty($this->params)) {
  834. $this->params = $params;
  835. } else {
  836. foreach ($params as $name => $value) {
  837. if (is_int($name)) {
  838. $this->params[] = $value;
  839. } else {
  840. $this->params[$name] = $value;
  841. }
  842. }
  843. }
  844. }
  845. return $this;
  846. }
  847. /**
  848. * Creates a new Query object and copies its property values from an existing one.
  849. * The properties being copies are the ones to be used by query builders.
  850. * @param Query $from the source query object
  851. * @return Query the new Query object
  852. */
  853. public static function create($from)
  854. {
  855. return new self([
  856. 'where' => $from->where,
  857. 'limit' => $from->limit,
  858. 'offset' => $from->offset,
  859. 'orderBy' => $from->orderBy,
  860. 'indexBy' => $from->indexBy,
  861. 'select' => $from->select,
  862. 'selectOption' => $from->selectOption,
  863. 'distinct' => $from->distinct,
  864. 'from' => $from->from,
  865. 'groupBy' => $from->groupBy,
  866. 'join' => $from->join,
  867. 'having' => $from->having,
  868. 'union' => $from->union,
  869. 'params' => $from->params,
  870. ]);
  871. }
  872. }