PageRenderTime 56ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/db/schema/CDbCriteria.php

https://github.com/ashie1287/headfirst
PHP | 499 lines | 231 code | 30 blank | 238 comment | 57 complexity | a14a00490f1b9c01110c0d0f06b82599 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, LGPL-2.1
  1. <?php
  2. /**
  3. * CDbCriteria class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2010 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CDbCriteria represents a query criteria, such as conditions, ordering by, limit/offset.
  12. *
  13. * @author Qiang Xue <qiang.xue@gmail.com>
  14. * @version $Id: CDbCriteria.php 2413 2010-09-02 02:19:56Z qiang.xue $
  15. * @package system.db.schema
  16. * @since 1.0
  17. */
  18. class CDbCriteria extends CComponent
  19. {
  20. const PARAM_PREFIX=':ycp';
  21. /**
  22. * @var integer the global counter for anonymous binding parameters.
  23. * This counter is used for generating the name for the anonymous parameters.
  24. */
  25. public static $paramCount=0;
  26. /**
  27. * @var mixed the columns being selected. This refers to the SELECT clause in an SQL
  28. * statement. The property can be either a string (column names separated by commas)
  29. * or an array of column names. Defaults to '*', meaning all columns.
  30. */
  31. public $select='*';
  32. /**
  33. * @var boolean whether to select distinct rows of data only. If this is set true,
  34. * the SELECT clause would be changed to SELECT DISTINCT.
  35. * @since 1.0.9
  36. */
  37. public $distinct=false;
  38. /**
  39. * @var string query condition. This refers to the WHERE clause in an SQL statement.
  40. * For example, <code>age>31 AND team=1</code>.
  41. */
  42. public $condition='';
  43. /**
  44. * @var array list of query parameter values indexed by parameter placeholders.
  45. * For example, <code>array(':name'=>'Dan', ':age'=>31)</code>.
  46. */
  47. public $params=array();
  48. /**
  49. * @var integer maximum number of records to be returned. If less than 0, it means no limit.
  50. */
  51. public $limit=-1;
  52. /**
  53. * @var integer zero-based offset from where the records are to be returned. If less than 0, it means starting from the beginning.
  54. */
  55. public $offset=-1;
  56. /**
  57. * @var string how to sort the query results. This refers to the ORDER BY clause in an SQL statement.
  58. */
  59. public $order='';
  60. /**
  61. * @var string how to group the query results. This refers to the GROUP BY clause in an SQL statement.
  62. * For example, <code>'projectID, teamID'</code>.
  63. */
  64. public $group='';
  65. /**
  66. * @var string how to join with other tables. This refers to the JOIN clause in an SQL statement.
  67. * For example, <code>'LEFT JOIN users ON users.id=authorID'</code>.
  68. */
  69. public $join='';
  70. /**
  71. * @var string the condition to be applied with GROUP-BY clause.
  72. * For example, <code>'SUM(revenue)<50000'</code>.
  73. * @since 1.0.1
  74. */
  75. public $having='';
  76. /**
  77. * @var array the relational query criteria. This is used for fetching related objects in eager loading fashion.
  78. * This property is effective only when the criteria is passed as a parameter to the following methods of CActiveRecord:
  79. * <ul>
  80. * <li>{@link CActiveRecord::find()}</li>
  81. * <li>{@link CActiveRecord::findAll()}</li>
  82. * <li>{@link CActiveRecord::findByPk()}</li>
  83. * <li>{@link CActiveRecord::findAllByPk()}</li>
  84. * <li>{@link CActiveRecord::findByAttributes()}</li>
  85. * <li>{@link CActiveRecord::findAllByAttributes()}</li>
  86. * <li>{@link CActiveRecord::count()}</li>
  87. * </ul>
  88. * The property value will be used as the parameter to the {@link CActiveRecord::with()} method
  89. * to perform the eager loading. Please refer to {@link CActiveRecord::with()} on how to specify this parameter.
  90. * @since 1.1.0
  91. */
  92. public $with;
  93. /**
  94. * @var string the alias name of the table. If not set, it means the alias is 't'.
  95. */
  96. public $alias;
  97. /**
  98. * @var boolean whether the foreign tables should be joined with the primary table in a single SQL.
  99. * This property is only used in relational AR queries.
  100. *
  101. * When this property is set true, only a single SQL will be executed for a relational AR query,
  102. * even if the primary table is limited and the relationship between a foreign table and the primary
  103. * table is many-to-one.
  104. *
  105. * When this property is set false, a SQL statement will be executed for each HAS_MANY relation.
  106. *
  107. * When this property is not set, if the primary table is limited, a SQL statement will be executed for each HAS_MANY relation.
  108. * Otherwise, a single SQL statement will be executed for all.
  109. *
  110. * @since 1.1.4
  111. */
  112. public $together;
  113. /**
  114. * Constructor.
  115. * @param array criteria initial property values (indexed by property name)
  116. */
  117. public function __construct($data=array())
  118. {
  119. foreach($data as $name=>$value)
  120. $this->$name=$value;
  121. }
  122. /**
  123. * Appends a condition to the existing {@link condition}.
  124. * The new condition and the existing condition will be concatenated via the specified operator
  125. * which defaults to 'AND'.
  126. * The new condition can also be an array. In this case, all elements in the array
  127. * will be concatenated together via the operator.
  128. * This method handles the case when the existing condition is empty.
  129. * After calling this method, the {@link condition} property will be modified.
  130. * @param mixed the new condition. It can be either a string or an array of strings.
  131. * @param string the operator to join different conditions. Defaults to 'AND'.
  132. * @return CDbCriteria the criteria object itself
  133. * @since 1.0.9
  134. */
  135. public function addCondition($condition,$operator='AND')
  136. {
  137. if(is_array($condition))
  138. {
  139. if($condition===array())
  140. return $this;
  141. $condition='('.implode(') '.$operator.' (',$condition).')';
  142. }
  143. if($this->condition==='')
  144. $this->condition=$condition;
  145. else
  146. $this->condition='('.$this->condition.') '.$operator.' ('.$condition.')';
  147. return $this;
  148. }
  149. /**
  150. * Appends a search condition to the existing {@link condition}.
  151. * The search condition and the existing condition will be concatenated via the specified operator
  152. * which defaults to 'AND'.
  153. * The search condition is generated using the SQL LIKE operator with the given column name and
  154. * search keyword.
  155. * @param string the column name (or a valid SQL expression)
  156. * @param string the search keyword. This interpretation of the keyword is affected by the next parameter.
  157. * @param boolean whether the keyword should be escaped if it contains characters % or _.
  158. * When this parameter is true (default), the special characters % (matches 0 or more characters)
  159. * and _ (matches a single character) will be escaped, and the keyword will be surrounded with a %
  160. * character on both ends. When this parameter is false, the keyword will be directly used for
  161. * matching without any change.
  162. * @param string the operator used to concatenate the new condition with the existing one.
  163. * Defaults to 'AND'.
  164. * @param string the LIKE operator. Defaults to 'LIKE'. You may also set this to be 'NOT LIKE'.
  165. * @return CDbCriteria the criteria object itself
  166. * @since 1.0.10
  167. */
  168. public function addSearchCondition($column,$keyword,$escape=true,$operator='AND',$like='LIKE')
  169. {
  170. if($escape)
  171. $keyword='%'.strtr($keyword,array('%'=>'\%', '_'=>'\_', '\\'=>'\\\\')).'%';
  172. $condition=$column." $like ".self::PARAM_PREFIX.self::$paramCount;
  173. $this->params[self::PARAM_PREFIX.self::$paramCount++]=$keyword;
  174. return $this->addCondition($condition, $operator);
  175. }
  176. /**
  177. * Appends an IN condition to the existing {@link condition}.
  178. * The IN condition and the existing condition will be concatenated via the specified operator
  179. * which defaults to 'AND'.
  180. * The IN condition is generated by using the SQL IN operator which requires the specified
  181. * column value to be among the given list of values.
  182. * @param string the column name (or a valid SQL expression)
  183. * @param array list of values that the column value should be in
  184. * @param string the operator used to concatenate the new condition with the existing one.
  185. * Defaults to 'AND'.
  186. * @return CDbCriteria the criteria object itself
  187. * @since 1.0.10
  188. */
  189. public function addInCondition($column,$values,$operator='AND')
  190. {
  191. if(($n=count($values))<1)
  192. return $this->addCondition('0=1',$operator); // 0=1 is used because in MSSQL value alone can't be used in WHERE
  193. if($n===1)
  194. {
  195. $value=reset($values);
  196. if($value===null)
  197. return $this->addCondition($column.' IS NULL');
  198. $condition=$column.'='.self::PARAM_PREFIX.self::$paramCount;
  199. $this->params[self::PARAM_PREFIX.self::$paramCount++]=$value;
  200. }
  201. else
  202. {
  203. $params=array();
  204. foreach($values as $value)
  205. {
  206. $params[]=self::PARAM_PREFIX.self::$paramCount;
  207. $this->params[self::PARAM_PREFIX.self::$paramCount++]=$value;
  208. }
  209. $condition=$column.' IN ('.implode(', ',$params).')';
  210. }
  211. return $this->addCondition($condition,$operator);
  212. }
  213. /**
  214. * Appends an NOT IN condition to the existing {@link condition}.
  215. * The NOT IN condition and the existing condition will be concatenated via the specified operator
  216. * which defaults to 'AND'.
  217. * The NOT IN condition is generated by using the SQL NOT IN operator which requires the specified
  218. * column value to be among the given list of values.
  219. * @param string the column name (or a valid SQL expression)
  220. * @param array list of values that the column value should be in
  221. * @param string the operator used to concatenate the new condition with the existing one.
  222. * Defaults to 'AND'.
  223. * @return CDbCriteria the criteria object itself
  224. * @since 1.1.1
  225. */
  226. public function addNotInCondition($column,$values,$operator='AND')
  227. {
  228. if(($n=count($values))<1)
  229. return $this;
  230. if($n===1)
  231. {
  232. $value=reset($values);
  233. if($value===null)
  234. return $this->addCondition($column.' IS NOT NULL');
  235. $condition=$column.'!='.self::PARAM_PREFIX.self::$paramCount;
  236. $this->params[self::PARAM_PREFIX.self::$paramCount++]=$value;
  237. }
  238. else
  239. {
  240. $params=array();
  241. foreach($values as $value)
  242. {
  243. $params[]=self::PARAM_PREFIX.self::$paramCount;
  244. $this->params[self::PARAM_PREFIX.self::$paramCount++]=$value;
  245. }
  246. $condition=$column.' NOT IN ('.implode(', ',$params).')';
  247. }
  248. return $this->addCondition($condition,$operator);
  249. }
  250. /**
  251. * Appends a condition for matching the given list of column values.
  252. * The generated condition will be concatenated to the existing {@link condition}
  253. * via the specified operator which defaults to 'AND'.
  254. * The condition is generated by matching each column and the corresponding value.
  255. * @param array list of column names and values to be matched (name=>value)
  256. * @param string the operator to concatenate multiple column matching condition. Defaults to 'AND'.
  257. * @param string the operator used to concatenate the new condition with the existing one.
  258. * Defaults to 'AND'.
  259. * @return CDbCriteria the criteria object itself
  260. * @since 1.0.10
  261. */
  262. public function addColumnCondition($columns,$columnOperator='AND',$operator='AND')
  263. {
  264. $params=array();
  265. foreach($columns as $name=>$value)
  266. {
  267. if($value===null)
  268. $params[]=$name.' IS NULL';
  269. else
  270. {
  271. $params[]=$name.'='.self::PARAM_PREFIX.self::$paramCount;
  272. $this->params[self::PARAM_PREFIX.self::$paramCount++]=$value;
  273. }
  274. }
  275. return $this->addCondition(implode(" $columnOperator ",$params), $operator);
  276. }
  277. /**
  278. * Adds a comparison expression to the {@link condition} property.
  279. *
  280. * This method is a helper that appends to the {@link condition} property
  281. * with a new comparison expression. The comparison is done by comparing a column
  282. * with the given value using some comparison operator.
  283. *
  284. * The comparison operator is intelligently determined based on the first few
  285. * characters in the given value. In particular, it recognizes the following operators
  286. * if they appear as the leading characters in the given value:
  287. * <ul>
  288. * <li><code>&lt;</code>: the column must be less than the given value.</li>
  289. * <li><code>&gt;</code>: the column must be greater than the given value.</li>
  290. * <li><code>&lt;=</code>: the column must be less than or equal to the given value.</li>
  291. * <li><code>&gt;=</code>: the column must be greater than or equal to the given value.</li>
  292. * <li><code>&lt;&gt;</code>: the column must not be the same as the given value.
  293. * Note that when $partialMatch is true, this would mean the value must not be a substring
  294. * of the column.</li>
  295. * <li><code>=</code>: the column must be equal to the given value.</li>
  296. * <li>none of the above: the column must be equal to the given value. Note that when $partialMatch
  297. * is true, this would mean the value must be the same as the given value or be a substring of it.</li>
  298. * </ul>
  299. *
  300. * Note that any surrounding white spaces will be removed from the value before comparison.
  301. * When the value is empty, no comparison expression will be added to the search condition.
  302. *
  303. * @param string the name of the column to be searched
  304. * @param mixed the column value to be compared with. If the value is a string, the aforementioned
  305. * intelligent comparison will be conducted. If the value is an array, the comparison is done
  306. * by exact match of any of the value in the array. If the string or the array is empty,
  307. * the existing search condition will not be modified.
  308. * @param boolean whether the value should consider partial text match (using LIKE and NOT LIKE operators).
  309. * Defaults to false, meaning exact comparison.
  310. * @param string the operator used to concatenate the new condition with the existing one.
  311. * Defaults to 'AND'.
  312. * @return CDbCriteria the criteria object itself
  313. * @since 1.1.1
  314. */
  315. public function compare($column, $value, $partialMatch=false, $operator='AND')
  316. {
  317. if(is_array($value))
  318. {
  319. if($value===array())
  320. return $this;
  321. return $this->addInCondition($column,$value,$operator);
  322. }
  323. else
  324. $value="$value";
  325. if(preg_match('/^(?:\s*(<>|<=|>=|<|>|=))?(.*)$/',$value,$matches))
  326. {
  327. $value=$matches[2];
  328. $op=$matches[1];
  329. }
  330. else
  331. $op='';
  332. if($value==='')
  333. return $this;
  334. if($partialMatch)
  335. {
  336. if($op==='')
  337. return $this->addSearchCondition($column,$value,true,$operator);
  338. if($op==='<>')
  339. return $this->addSearchCondition($column,$value,true,$operator,'NOT LIKE');
  340. }
  341. else if($op==='')
  342. $op='=';
  343. $this->addCondition($column.$op.self::PARAM_PREFIX.self::$paramCount,$operator);
  344. $this->params[self::PARAM_PREFIX.self::$paramCount++]=$value;
  345. return $this;
  346. }
  347. /**
  348. * Adds a between condition to the {@link condition} property.
  349. *
  350. * The new between condition and the existing condition will be concatenated via
  351. * the specified operator which defaults to 'AND'.
  352. * If one or both values are empty then the condition is not added to the existing condition.
  353. * This method handles the case when the existing condition is empty.
  354. * After calling this method, the {@link condition} property will be modified.
  355. * @param string the name of the column to search between.
  356. * @param string the beginning value to start the between search.
  357. * @param string the ending value to end the between search.
  358. * @param string the operator used to concatenate the new condition with the existing one.
  359. * Defaults to 'AND'.
  360. * @return CDbCriteria the criteria object itself
  361. * @since 1.1.2
  362. */
  363. public function addBetweenCondition($column,$valueStart,$valueEnd,$operator='AND')
  364. {
  365. if($valueStart==='' || $valueEnd==='')
  366. return $this;
  367. $paramStart=self::PARAM_PREFIX.self::$paramCount++;
  368. $paramEnd=self::PARAM_PREFIX.self::$paramCount++;
  369. $this->params[$paramStart]=$valueStart;
  370. $this->params[$paramEnd]=$valueEnd;
  371. $condition="$column BETWEEN $paramStart AND $paramEnd";
  372. if($this->condition==='')
  373. $this->condition=$condition;
  374. else
  375. $this->condition='('.$this->condition.') '.$operator.' ('.$condition.')';
  376. return $this;
  377. }
  378. /**
  379. * Merges with another criteria.
  380. * In general, the merging makes the resulting criteria more restrictive.
  381. * For example, if both criterias have conditions, they will be 'AND' together.
  382. * Also, the criteria passed as the parameter takes precedence in case
  383. * two options cannot be merged (e.g. LIMIT, OFFSET).
  384. * @param CDbCriteria the criteria to be merged with.
  385. * @param boolean whether to use 'AND' to merge condition and having options.
  386. * If false, 'OR' will be used instead. Defaults to 'AND'. This parameter has been
  387. * available since version 1.0.6.
  388. * @since 1.0.5
  389. */
  390. public function mergeWith($criteria,$useAnd=true)
  391. {
  392. $and=$useAnd ? 'AND' : 'OR';
  393. if(is_array($criteria))
  394. $criteria=new self($criteria);
  395. if($this->select!==$criteria->select)
  396. {
  397. if($this->select==='*')
  398. $this->select=$criteria->select;
  399. else if($criteria->select!=='*')
  400. {
  401. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  402. $select2=is_string($criteria->select)?preg_split('/\s*,\s*/',trim($criteria->select),-1,PREG_SPLIT_NO_EMPTY):$criteria->select;
  403. $this->select=array_merge($select1,array_diff($select2,$select1));
  404. }
  405. }
  406. if($this->condition!==$criteria->condition)
  407. {
  408. if($this->condition==='')
  409. $this->condition=$criteria->condition;
  410. else if($criteria->condition!=='')
  411. $this->condition="({$this->condition}) $and ({$criteria->condition})";
  412. }
  413. if($this->params!==$criteria->params)
  414. $this->params=array_merge($this->params,$criteria->params);
  415. if($criteria->limit>0)
  416. $this->limit=$criteria->limit;
  417. if($criteria->offset>=0)
  418. $this->offset=$criteria->offset;
  419. if($criteria->alias!==null)
  420. $this->alias=$criteria->alias;
  421. if($this->order!==$criteria->order)
  422. {
  423. if($this->order==='')
  424. $this->order=$criteria->order;
  425. else if($criteria->order!=='')
  426. $this->order=$criteria->order.', '.$this->order;
  427. }
  428. if($this->group!==$criteria->group)
  429. {
  430. if($this->group==='')
  431. $this->group=$criteria->group;
  432. else if($criteria->group!=='')
  433. $this->group.=', '.$criteria->group;
  434. }
  435. if($this->join!==$criteria->join)
  436. {
  437. if($this->join==='')
  438. $this->join=$criteria->join;
  439. else if($criteria->join!=='')
  440. $this->join.=' '.$criteria->join;
  441. }
  442. if($this->having!==$criteria->having)
  443. {
  444. if($this->having==='')
  445. $this->having=$criteria->having;
  446. else if($criteria->having!=='')
  447. $this->having="({$this->having}) $and ({$criteria->having})";
  448. }
  449. if($criteria->distinct>0)
  450. $this->distinct=$criteria->distinct;
  451. if($criteria->together!==null)
  452. $this->together=$criteria->together;
  453. if(empty($this->with))
  454. $this->with=$criteria->with;
  455. else if(!empty($criteria->with))
  456. $this->with=CMap::mergeArray($this->with, $criteria->with);
  457. }
  458. /**
  459. * @return array the array representation of the criteria
  460. * @since 1.0.6
  461. */
  462. public function toArray()
  463. {
  464. $result=array();
  465. foreach(array('select', 'condition', 'params', 'limit', 'offset', 'order', 'group', 'join', 'having', 'distinct', 'with', 'alias', 'together') as $name)
  466. $result[$name]=$this->$name;
  467. return $result;
  468. }
  469. }