Query.php 40 KB

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