PageRenderTime 34ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/protected/extensions/bootstrap/demo/yii/db/ar/CActiveRecord.php

https://bitbucket.org/negge/tlklan2
PHP | 2337 lines | 1120 code | 157 blank | 1060 comment | 208 complexity | 4e7d014a13142101c44e39e68fbae32d MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, BSD-2-Clause, GPL-3.0
  1. <?php
  2. /**
  3. * CActiveRecord class file.
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright &copy; 2008-2011 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CActiveRecord is the base class for classes representing relational data.
  12. *
  13. * It implements the active record design pattern, a popular Object-Relational Mapping (ORM) technique.
  14. * Please check {@link http://www.yiiframework.com/doc/guide/database.ar the Guide} for more details
  15. * about this class.
  16. *
  17. * @property CDbCriteria $dbCriteria The query criteria that is associated with this model.
  18. * This criteria is mainly used by {@link scopes named scope} feature to accumulate
  19. * different criteria specifications.
  20. * @property CActiveRecordMetaData $metaData The meta for this AR class.
  21. * @property CDbConnection $dbConnection The database connection used by active record.
  22. * @property CDbTableSchema $tableSchema The metadata of the table that this AR belongs to.
  23. * @property CDbCommandBuilder $commandBuilder The command builder used by this AR.
  24. * @property array $attributes Attribute values indexed by attribute names.
  25. * @property boolean $isNewRecord Whether the record is new and should be inserted when calling {@link save}.
  26. * This property is automatically set in constructor and {@link populateRecord}.
  27. * Defaults to false, but it will be set to true if the instance is created using
  28. * the new operator.
  29. * @property mixed $primaryKey The primary key value. An array (column name=>column value) is returned if the primary key is composite.
  30. * If primary key is not defined, null will be returned.
  31. * @property mixed $oldPrimaryKey The old primary key value. An array (column name=>column value) is returned if the primary key is composite.
  32. * If primary key is not defined, null will be returned.
  33. * @property string $tableAlias The default table alias.
  34. *
  35. * @author Qiang Xue <qiang.xue@gmail.com>
  36. * @version $Id$
  37. * @package system.db.ar
  38. * @since 1.0
  39. */
  40. abstract class CActiveRecord extends CModel
  41. {
  42. const BELONGS_TO='CBelongsToRelation';
  43. const HAS_ONE='CHasOneRelation';
  44. const HAS_MANY='CHasManyRelation';
  45. const MANY_MANY='CManyManyRelation';
  46. const STAT='CStatRelation';
  47. /**
  48. * @var CDbConnection the default database connection for all active record classes.
  49. * By default, this is the 'db' application component.
  50. * @see getDbConnection
  51. */
  52. public static $db;
  53. private static $_models=array(); // class name => model
  54. private $_md; // meta data
  55. private $_new=false; // whether this instance is new or not
  56. private $_attributes=array(); // attribute name => attribute value
  57. private $_related=array(); // attribute name => related objects
  58. private $_c; // query criteria (used by finder only)
  59. private $_pk; // old primary key value
  60. private $_alias='t'; // the table alias being used for query
  61. /**
  62. * Constructor.
  63. * @param string $scenario scenario name. See {@link CModel::scenario} for more details about this parameter.
  64. */
  65. public function __construct($scenario='insert')
  66. {
  67. if($scenario===null) // internally used by populateRecord() and model()
  68. return;
  69. $this->setScenario($scenario);
  70. $this->setIsNewRecord(true);
  71. $this->_attributes=$this->getMetaData()->attributeDefaults;
  72. $this->init();
  73. $this->attachBehaviors($this->behaviors());
  74. $this->afterConstruct();
  75. }
  76. /**
  77. * Initializes this model.
  78. * This method is invoked when an AR instance is newly created and has
  79. * its {@link scenario} set.
  80. * You may override this method to provide code that is needed to initialize the model (e.g. setting
  81. * initial property values.)
  82. */
  83. public function init()
  84. {
  85. }
  86. /**
  87. * Sets the parameters about query caching.
  88. * This is a shortcut method to {@link CDbConnection::cache()}.
  89. * It changes the query caching parameter of the {@link dbConnection} instance.
  90. * @param integer $duration the number of seconds that query results may remain valid in cache.
  91. * If this is 0, the caching will be disabled.
  92. * @param CCacheDependency $dependency the dependency that will be used when saving the query results into cache.
  93. * @param integer $queryCount number of SQL queries that need to be cached after calling this method. Defaults to 1,
  94. * meaning that the next SQL query will be cached.
  95. * @return CActiveRecord the active record instance itself.
  96. * @since 1.1.7
  97. */
  98. public function cache($duration, $dependency=null, $queryCount=1)
  99. {
  100. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  101. return $this;
  102. }
  103. /**
  104. * PHP sleep magic method.
  105. * This method ensures that the model meta data reference is set to null.
  106. * @return array
  107. */
  108. public function __sleep()
  109. {
  110. $this->_md=null;
  111. return array_keys((array)$this);
  112. }
  113. /**
  114. * PHP getter magic method.
  115. * This method is overridden so that AR attributes can be accessed like properties.
  116. * @param string $name property name
  117. * @return mixed property value
  118. * @see getAttribute
  119. */
  120. public function __get($name)
  121. {
  122. if(isset($this->_attributes[$name]))
  123. return $this->_attributes[$name];
  124. else if(isset($this->getMetaData()->columns[$name]))
  125. return null;
  126. else if(isset($this->_related[$name]))
  127. return $this->_related[$name];
  128. else if(isset($this->getMetaData()->relations[$name]))
  129. return $this->getRelated($name);
  130. else
  131. return parent::__get($name);
  132. }
  133. /**
  134. * PHP setter magic method.
  135. * This method is overridden so that AR attributes can be accessed like properties.
  136. * @param string $name property name
  137. * @param mixed $value property value
  138. */
  139. public function __set($name,$value)
  140. {
  141. if($this->setAttribute($name,$value)===false)
  142. {
  143. if(isset($this->getMetaData()->relations[$name]))
  144. $this->_related[$name]=$value;
  145. else
  146. parent::__set($name,$value);
  147. }
  148. }
  149. /**
  150. * Checks if a property value is null.
  151. * This method overrides the parent implementation by checking
  152. * if the named attribute is null or not.
  153. * @param string $name the property name or the event name
  154. * @return boolean whether the property value is null
  155. */
  156. public function __isset($name)
  157. {
  158. if(isset($this->_attributes[$name]))
  159. return true;
  160. else if(isset($this->getMetaData()->columns[$name]))
  161. return false;
  162. else if(isset($this->_related[$name]))
  163. return true;
  164. else if(isset($this->getMetaData()->relations[$name]))
  165. return $this->getRelated($name)!==null;
  166. else
  167. return parent::__isset($name);
  168. }
  169. /**
  170. * Sets a component property to be null.
  171. * This method overrides the parent implementation by clearing
  172. * the specified attribute value.
  173. * @param string $name the property name or the event name
  174. */
  175. public function __unset($name)
  176. {
  177. if(isset($this->getMetaData()->columns[$name]))
  178. unset($this->_attributes[$name]);
  179. else if(isset($this->getMetaData()->relations[$name]))
  180. unset($this->_related[$name]);
  181. else
  182. parent::__unset($name);
  183. }
  184. /**
  185. * Calls the named method which is not a class method.
  186. * Do not call this method. This is a PHP magic method that we override
  187. * to implement the named scope feature.
  188. * @param string $name the method name
  189. * @param array $parameters method parameters
  190. * @return mixed the method return value
  191. */
  192. public function __call($name,$parameters)
  193. {
  194. if(isset($this->getMetaData()->relations[$name]))
  195. {
  196. if(empty($parameters))
  197. return $this->getRelated($name,false);
  198. else
  199. return $this->getRelated($name,false,$parameters[0]);
  200. }
  201. $scopes=$this->scopes();
  202. if(isset($scopes[$name]))
  203. {
  204. $this->getDbCriteria()->mergeWith($scopes[$name]);
  205. return $this;
  206. }
  207. return parent::__call($name,$parameters);
  208. }
  209. /**
  210. * Returns the related record(s).
  211. * This method will return the related record(s) of the current record.
  212. * If the relation is HAS_ONE or BELONGS_TO, it will return a single object
  213. * or null if the object does not exist.
  214. * If the relation is HAS_MANY or MANY_MANY, it will return an array of objects
  215. * or an empty array.
  216. * @param string $name the relation name (see {@link relations})
  217. * @param boolean $refresh whether to reload the related objects from database. Defaults to false.
  218. * @param mixed $params array or CDbCriteria object with additional parameters that customize the query conditions as specified in the relation declaration.
  219. * @return mixed the related object(s).
  220. * @throws CDbException if the relation is not specified in {@link relations}.
  221. */
  222. public function getRelated($name,$refresh=false,$params=array())
  223. {
  224. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  225. return $this->_related[$name];
  226. $md=$this->getMetaData();
  227. if(!isset($md->relations[$name]))
  228. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  229. array('{class}'=>get_class($this), '{name}'=>$name)));
  230. Yii::trace('lazy loading '.get_class($this).'.'.$name,'system.db.ar.CActiveRecord');
  231. $relation=$md->relations[$name];
  232. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  233. return $relation instanceof CHasOneRelation ? null : array();
  234. if($params!==array()) // dynamic query
  235. {
  236. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  237. if($exists)
  238. $save=$this->_related[$name];
  239. if($params instanceof CDbCriteria)
  240. $params = $params->toArray();
  241. $r=array($name=>$params);
  242. }
  243. else
  244. $r=$name;
  245. unset($this->_related[$name]);
  246. $finder=new CActiveFinder($this,$r);
  247. $finder->lazyFind($this);
  248. if(!isset($this->_related[$name]))
  249. {
  250. if($relation instanceof CHasManyRelation)
  251. $this->_related[$name]=array();
  252. else if($relation instanceof CStatRelation)
  253. $this->_related[$name]=$relation->defaultValue;
  254. else
  255. $this->_related[$name]=null;
  256. }
  257. if($params!==array())
  258. {
  259. $results=$this->_related[$name];
  260. if($exists)
  261. $this->_related[$name]=$save;
  262. else
  263. unset($this->_related[$name]);
  264. return $results;
  265. }
  266. else
  267. return $this->_related[$name];
  268. }
  269. /**
  270. * Returns a value indicating whether the named related object(s) has been loaded.
  271. * @param string $name the relation name
  272. * @return boolean a value indicating whether the named related object(s) has been loaded.
  273. */
  274. public function hasRelated($name)
  275. {
  276. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  277. }
  278. /**
  279. * Returns the query criteria associated with this model.
  280. * @param boolean $createIfNull whether to create a criteria instance if it does not exist. Defaults to true.
  281. * @return CDbCriteria the query criteria that is associated with this model.
  282. * This criteria is mainly used by {@link scopes named scope} feature to accumulate
  283. * different criteria specifications.
  284. */
  285. public function getDbCriteria($createIfNull=true)
  286. {
  287. if($this->_c===null)
  288. {
  289. if(($c=$this->defaultScope())!==array() || $createIfNull)
  290. $this->_c=new CDbCriteria($c);
  291. }
  292. return $this->_c;
  293. }
  294. /**
  295. * Sets the query criteria for the current model.
  296. * @param CDbCriteria $criteria the query criteria
  297. * @since 1.1.3
  298. */
  299. public function setDbCriteria($criteria)
  300. {
  301. $this->_c=$criteria;
  302. }
  303. /**
  304. * Returns the default named scope that should be implicitly applied to all queries for this model.
  305. * Note, default scope only applies to SELECT queries. It is ignored for INSERT, UPDATE and DELETE queries.
  306. * The default implementation simply returns an empty array. You may override this method
  307. * if the model needs to be queried with some default criteria (e.g. only active records should be returned).
  308. * @return array the query criteria. This will be used as the parameter to the constructor
  309. * of {@link CDbCriteria}.
  310. */
  311. public function defaultScope()
  312. {
  313. return array();
  314. }
  315. /**
  316. * Resets all scopes and criterias applied including default scope.
  317. *
  318. * @return CActiveRecord
  319. * @since 1.1.2
  320. */
  321. public function resetScope()
  322. {
  323. $this->_c=new CDbCriteria();
  324. return $this;
  325. }
  326. /**
  327. * Returns the static model of the specified AR class.
  328. * The model returned is a static instance of the AR class.
  329. * It is provided for invoking class-level methods (something similar to static class methods.)
  330. *
  331. * EVERY derived AR class must override this method as follows,
  332. * <pre>
  333. * public static function model($className=__CLASS__)
  334. * {
  335. * return parent::model($className);
  336. * }
  337. * </pre>
  338. *
  339. * @param string $className active record class name.
  340. * @return CActiveRecord active record model instance.
  341. */
  342. public static function model($className=__CLASS__)
  343. {
  344. if(isset(self::$_models[$className]))
  345. return self::$_models[$className];
  346. else
  347. {
  348. $model=self::$_models[$className]=new $className(null);
  349. $model->_md=new CActiveRecordMetaData($model);
  350. $model->attachBehaviors($model->behaviors());
  351. return $model;
  352. }
  353. }
  354. /**
  355. * Returns the meta-data for this AR
  356. * @return CActiveRecordMetaData the meta for this AR class.
  357. */
  358. public function getMetaData()
  359. {
  360. if($this->_md!==null)
  361. return $this->_md;
  362. else
  363. return $this->_md=self::model(get_class($this))->_md;
  364. }
  365. /**
  366. * Refreshes the meta data for this AR class.
  367. * By calling this method, this AR class will regenerate the meta data needed.
  368. * This is useful if the table schema has been changed and you want to use the latest
  369. * available table schema. Make sure you have called {@link CDbSchema::refresh}
  370. * before you call this method. Otherwise, old table schema data will still be used.
  371. */
  372. public function refreshMetaData()
  373. {
  374. $finder=self::model(get_class($this));
  375. $finder->_md=new CActiveRecordMetaData($finder);
  376. if($this!==$finder)
  377. $this->_md=$finder->_md;
  378. }
  379. /**
  380. * Returns the name of the associated database table.
  381. * By default this method returns the class name as the table name.
  382. * You may override this method if the table is not named after this convention.
  383. * @return string the table name
  384. */
  385. public function tableName()
  386. {
  387. return get_class($this);
  388. }
  389. /**
  390. * Returns the primary key of the associated database table.
  391. * This method is meant to be overridden in case when the table is not defined with a primary key
  392. * (for some legency database). If the table is already defined with a primary key,
  393. * you do not need to override this method. The default implementation simply returns null,
  394. * meaning using the primary key defined in the database.
  395. * @return mixed the primary key of the associated database table.
  396. * If the key is a single column, it should return the column name;
  397. * If the key is a composite one consisting of several columns, it should
  398. * return the array of the key column names.
  399. */
  400. public function primaryKey()
  401. {
  402. }
  403. /**
  404. * This method should be overridden to declare related objects.
  405. *
  406. * There are four types of relations that may exist between two active record objects:
  407. * <ul>
  408. * <li>BELONGS_TO: e.g. a member belongs to a team;</li>
  409. * <li>HAS_ONE: e.g. a member has at most one profile;</li>
  410. * <li>HAS_MANY: e.g. a team has many members;</li>
  411. * <li>MANY_MANY: e.g. a member has many skills and a skill belongs to a member.</li>
  412. * </ul>
  413. *
  414. * Besides the above relation types, a special relation called STAT is also supported
  415. * that can be used to perform statistical query (or aggregational query).
  416. * It retrieves the aggregational information about the related objects, such as the number
  417. * of comments for each post, the average rating for each product, etc.
  418. *
  419. * Each kind of related objects is defined in this method as an array with the following elements:
  420. * <pre>
  421. * 'varName'=>array('relationType', 'className', 'foreign_key', ...additional options)
  422. * </pre>
  423. * where 'varName' refers to the name of the variable/property that the related object(s) can
  424. * be accessed through; 'relationType' refers to the type of the relation, which can be one of the
  425. * following four constants: self::BELONGS_TO, self::HAS_ONE, self::HAS_MANY and self::MANY_MANY;
  426. * 'className' refers to the name of the active record class that the related object(s) is of;
  427. * and 'foreign_key' states the foreign key that relates the two kinds of active record.
  428. * Note, for composite foreign keys, they can be either listed together, separated by commas or specified as an array
  429. * in format of array('key1','key2'). In case you need to specify custom PK->FK association you can define it as
  430. * array('fk'=>'pk'). For composite keys it will be array('fk_c1'=>'pk_с1','fk_c2'=>'pk_c2').
  431. * For foreign keys used in MANY_MANY relation, the joining table must be declared as well
  432. * (e.g. 'join_table(fk1, fk2)').
  433. *
  434. * Additional options may be specified as name-value pairs in the rest array elements:
  435. * <ul>
  436. * <li>'select': string|array, a list of columns to be selected. Defaults to '*', meaning all columns.
  437. * Column names should be disambiguated if they appear in an expression (e.g. COUNT(relationName.name) AS name_count).</li>
  438. * <li>'condition': string, the WHERE clause. Defaults to empty. Note, column references need to
  439. * be disambiguated with prefix 'relationName.' (e.g. relationName.age&gt;20)</li>
  440. * <li>'order': string, the ORDER BY clause. Defaults to empty. Note, column references need to
  441. * be disambiguated with prefix 'relationName.' (e.g. relationName.age DESC)</li>
  442. * <li>'with': string|array, a list of child related objects that should be loaded together with this object.
  443. * Note, this is only honored by lazy loading, not eager loading.</li>
  444. * <li>'joinType': type of join. Defaults to 'LEFT OUTER JOIN'.</li>
  445. * <li>'alias': the alias for the table associated with this relationship.
  446. * It defaults to null,
  447. * meaning the table alias is the same as the relation name.</li>
  448. * <li>'params': the parameters to be bound to the generated SQL statement.
  449. * This should be given as an array of name-value pairs.</li>
  450. * <li>'on': the ON clause. The condition specified here will be appended
  451. * to the joining condition using the AND operator.</li>
  452. * <li>'index': the name of the column whose values should be used as keys
  453. * of the array that stores related objects. This option is only available to
  454. * HAS_MANY and MANY_MANY relations.</li>
  455. * <li>'scopes': scopes to apply. In case of a single scope can be used like 'scopes'=>'scopeName',
  456. * in case of multiple scopes can be used like 'scopes'=>array('scopeName1','scopeName2').
  457. * This option has been available since version 1.1.9.</li>
  458. * </ul>
  459. *
  460. * The following options are available for certain relations when lazy loading:
  461. * <ul>
  462. * <li>'group': string, the GROUP BY clause. Defaults to empty. Note, column references need to
  463. * be disambiguated with prefix 'relationName.' (e.g. relationName.age). This option only applies to HAS_MANY and MANY_MANY relations.</li>
  464. * <li>'having': string, the HAVING clause. Defaults to empty. Note, column references need to
  465. * be disambiguated with prefix 'relationName.' (e.g. relationName.age). This option only applies to HAS_MANY and MANY_MANY relations.</li>
  466. * <li>'limit': limit of the rows to be selected. This option does not apply to BELONGS_TO relation.</li>
  467. * <li>'offset': offset of the rows to be selected. This option does not apply to BELONGS_TO relation.</li>
  468. * <li>'through': name of the model's relation that will be used as a bridge when getting related data. Can be set only for HAS_ONE and HAS_MANY. This option has been available since version 1.1.7.</li>
  469. * </ul>
  470. *
  471. * Below is an example declaring related objects for 'Post' active record class:
  472. * <pre>
  473. * return array(
  474. * 'author'=>array(self::BELONGS_TO, 'User', 'author_id'),
  475. * 'comments'=>array(self::HAS_MANY, 'Comment', 'post_id', 'with'=>'author', 'order'=>'create_time DESC'),
  476. * 'tags'=>array(self::MANY_MANY, 'Tag', 'post_tag(post_id, tag_id)', 'order'=>'name'),
  477. * );
  478. * </pre>
  479. *
  480. * @return array list of related object declarations. Defaults to empty array.
  481. */
  482. public function relations()
  483. {
  484. return array();
  485. }
  486. /**
  487. * Returns the declaration of named scopes.
  488. * A named scope represents a query criteria that can be chained together with
  489. * other named scopes and applied to a query. This method should be overridden
  490. * by child classes to declare named scopes for the particular AR classes.
  491. * For example, the following code declares two named scopes: 'recently' and
  492. * 'published'.
  493. * <pre>
  494. * return array(
  495. * 'published'=>array(
  496. * 'condition'=>'status=1',
  497. * ),
  498. * 'recently'=>array(
  499. * 'order'=>'create_time DESC',
  500. * 'limit'=>5,
  501. * ),
  502. * );
  503. * </pre>
  504. * If the above scopes are declared in a 'Post' model, we can perform the following
  505. * queries:
  506. * <pre>
  507. * $posts=Post::model()->published()->findAll();
  508. * $posts=Post::model()->published()->recently()->findAll();
  509. * $posts=Post::model()->published()->with('comments')->findAll();
  510. * </pre>
  511. * Note that the last query is a relational query.
  512. *
  513. * @return array the scope definition. The array keys are scope names; the array
  514. * values are the corresponding scope definitions. Each scope definition is represented
  515. * as an array whose keys must be properties of {@link CDbCriteria}.
  516. */
  517. public function scopes()
  518. {
  519. return array();
  520. }
  521. /**
  522. * Returns the list of all attribute names of the model.
  523. * This would return all column names of the table associated with this AR class.
  524. * @return array list of attribute names.
  525. */
  526. public function attributeNames()
  527. {
  528. return array_keys($this->getMetaData()->columns);
  529. }
  530. /**
  531. * Returns the text label for the specified attribute.
  532. * This method overrides the parent implementation by supporting
  533. * returning the label defined in relational object.
  534. * In particular, if the attribute name is in the form of "post.author.name",
  535. * then this method will derive the label from the "author" relation's "name" attribute.
  536. * @param string $attribute the attribute name
  537. * @return string the attribute label
  538. * @see generateAttributeLabel
  539. * @since 1.1.4
  540. */
  541. public function getAttributeLabel($attribute)
  542. {
  543. $labels=$this->attributeLabels();
  544. if(isset($labels[$attribute]))
  545. return $labels[$attribute];
  546. else if(strpos($attribute,'.')!==false)
  547. {
  548. $segs=explode('.',$attribute);
  549. $name=array_pop($segs);
  550. $model=$this;
  551. foreach($segs as $seg)
  552. {
  553. $relations=$model->getMetaData()->relations;
  554. if(isset($relations[$seg]))
  555. $model=CActiveRecord::model($relations[$seg]->className);
  556. else
  557. break;
  558. }
  559. return $model->getAttributeLabel($name);
  560. }
  561. else
  562. return $this->generateAttributeLabel($attribute);
  563. }
  564. /**
  565. * Returns the database connection used by active record.
  566. * By default, the "db" application component is used as the database connection.
  567. * You may override this method if you want to use a different database connection.
  568. * @return CDbConnection the database connection used by active record.
  569. */
  570. public function getDbConnection()
  571. {
  572. if(self::$db!==null)
  573. return self::$db;
  574. else
  575. {
  576. self::$db=Yii::app()->getDb();
  577. if(self::$db instanceof CDbConnection)
  578. return self::$db;
  579. else
  580. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  581. }
  582. }
  583. /**
  584. * Returns the named relation declared for this AR class.
  585. * @param string $name the relation name
  586. * @return CActiveRelation the named relation declared for this AR class. Null if the relation does not exist.
  587. */
  588. public function getActiveRelation($name)
  589. {
  590. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  591. }
  592. /**
  593. * Returns the metadata of the table that this AR belongs to
  594. * @return CDbTableSchema the metadata of the table that this AR belongs to
  595. */
  596. public function getTableSchema()
  597. {
  598. return $this->getMetaData()->tableSchema;
  599. }
  600. /**
  601. * Returns the command builder used by this AR.
  602. * @return CDbCommandBuilder the command builder used by this AR
  603. */
  604. public function getCommandBuilder()
  605. {
  606. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  607. }
  608. /**
  609. * Checks whether this AR has the named attribute
  610. * @param string $name attribute name
  611. * @return boolean whether this AR has the named attribute (table column).
  612. */
  613. public function hasAttribute($name)
  614. {
  615. return isset($this->getMetaData()->columns[$name]);
  616. }
  617. /**
  618. * Returns the named attribute value.
  619. * If this is a new record and the attribute is not set before,
  620. * the default column value will be returned.
  621. * If this record is the result of a query and the attribute is not loaded,
  622. * null will be returned.
  623. * You may also use $this->AttributeName to obtain the attribute value.
  624. * @param string $name the attribute name
  625. * @return mixed the attribute value. Null if the attribute is not set or does not exist.
  626. * @see hasAttribute
  627. */
  628. public function getAttribute($name)
  629. {
  630. if(property_exists($this,$name))
  631. return $this->$name;
  632. else if(isset($this->_attributes[$name]))
  633. return $this->_attributes[$name];
  634. }
  635. /**
  636. * Sets the named attribute value.
  637. * You may also use $this->AttributeName to set the attribute value.
  638. * @param string $name the attribute name
  639. * @param mixed $value the attribute value.
  640. * @return boolean whether the attribute exists and the assignment is conducted successfully
  641. * @see hasAttribute
  642. */
  643. public function setAttribute($name,$value)
  644. {
  645. if(property_exists($this,$name))
  646. $this->$name=$value;
  647. else if(isset($this->getMetaData()->columns[$name]))
  648. $this->_attributes[$name]=$value;
  649. else
  650. return false;
  651. return true;
  652. }
  653. /**
  654. * Do not call this method. This method is used internally by {@link CActiveFinder} to populate
  655. * related objects. This method adds a related object to this record.
  656. * @param string $name attribute name
  657. * @param mixed $record the related record
  658. * @param mixed $index the index value in the related object collection.
  659. * If true, it means using zero-based integer index.
  660. * If false, it means a HAS_ONE or BELONGS_TO object and no index is needed.
  661. */
  662. public function addRelatedRecord($name,$record,$index)
  663. {
  664. if($index!==false)
  665. {
  666. if(!isset($this->_related[$name]))
  667. $this->_related[$name]=array();
  668. if($record instanceof CActiveRecord)
  669. {
  670. if($index===true)
  671. $this->_related[$name][]=$record;
  672. else
  673. $this->_related[$name][$index]=$record;
  674. }
  675. }
  676. else if(!isset($this->_related[$name]))
  677. $this->_related[$name]=$record;
  678. }
  679. /**
  680. * Returns all column attribute values.
  681. * Note, related objects are not returned.
  682. * @param mixed $names names of attributes whose value needs to be returned.
  683. * If this is true (default), then all attribute values will be returned, including
  684. * those that are not loaded from DB (null will be returned for those attributes).
  685. * If this is null, all attributes except those that are not loaded from DB will be returned.
  686. * @return array attribute values indexed by attribute names.
  687. */
  688. public function getAttributes($names=true)
  689. {
  690. $attributes=$this->_attributes;
  691. foreach($this->getMetaData()->columns as $name=>$column)
  692. {
  693. if(property_exists($this,$name))
  694. $attributes[$name]=$this->$name;
  695. else if($names===true && !isset($attributes[$name]))
  696. $attributes[$name]=null;
  697. }
  698. if(is_array($names))
  699. {
  700. $attrs=array();
  701. foreach($names as $name)
  702. {
  703. if(property_exists($this,$name))
  704. $attrs[$name]=$this->$name;
  705. else
  706. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  707. }
  708. return $attrs;
  709. }
  710. else
  711. return $attributes;
  712. }
  713. /**
  714. * Saves the current record.
  715. *
  716. * The record is inserted as a row into the database table if its {@link isNewRecord}
  717. * property is true (usually the case when the record is created using the 'new'
  718. * operator). Otherwise, it will be used to update the corresponding row in the table
  719. * (usually the case if the record is obtained using one of those 'find' methods.)
  720. *
  721. * Validation will be performed before saving the record. If the validation fails,
  722. * the record will not be saved. You can call {@link getErrors()} to retrieve the
  723. * validation errors.
  724. *
  725. * If the record is saved via insertion, its {@link isNewRecord} property will be
  726. * set false, and its {@link scenario} property will be set to be 'update'.
  727. * And if its primary key is auto-incremental and is not set before insertion,
  728. * the primary key will be populated with the automatically generated key value.
  729. *
  730. * @param boolean $runValidation whether to perform validation before saving the record.
  731. * If the validation fails, the record will not be saved to database.
  732. * @param array $attributes list of attributes that need to be saved. Defaults to null,
  733. * meaning all attributes that are loaded from DB will be saved.
  734. * @return boolean whether the saving succeeds
  735. */
  736. public function save($runValidation=true,$attributes=null)
  737. {
  738. if(!$runValidation || $this->validate($attributes))
  739. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  740. else
  741. return false;
  742. }
  743. /**
  744. * Returns if the current record is new.
  745. * @return boolean whether the record is new and should be inserted when calling {@link save}.
  746. * This property is automatically set in constructor and {@link populateRecord}.
  747. * Defaults to false, but it will be set to true if the instance is created using
  748. * the new operator.
  749. */
  750. public function getIsNewRecord()
  751. {
  752. return $this->_new;
  753. }
  754. /**
  755. * Sets if the record is new.
  756. * @param boolean $value whether the record is new and should be inserted when calling {@link save}.
  757. * @see getIsNewRecord
  758. */
  759. public function setIsNewRecord($value)
  760. {
  761. $this->_new=$value;
  762. }
  763. /**
  764. * This event is raised before the record is saved.
  765. * By setting {@link CModelEvent::isValid} to be false, the normal {@link save()} process will be stopped.
  766. * @param CModelEvent $event the event parameter
  767. */
  768. public function onBeforeSave($event)
  769. {
  770. $this->raiseEvent('onBeforeSave',$event);
  771. }
  772. /**
  773. * This event is raised after the record is saved.
  774. * @param CEvent $event the event parameter
  775. */
  776. public function onAfterSave($event)
  777. {
  778. $this->raiseEvent('onAfterSave',$event);
  779. }
  780. /**
  781. * This event is raised before the record is deleted.
  782. * By setting {@link CModelEvent::isValid} to be false, the normal {@link delete()} process will be stopped.
  783. * @param CModelEvent $event the event parameter
  784. */
  785. public function onBeforeDelete($event)
  786. {
  787. $this->raiseEvent('onBeforeDelete',$event);
  788. }
  789. /**
  790. * This event is raised after the record is deleted.
  791. * @param CEvent $event the event parameter
  792. */
  793. public function onAfterDelete($event)
  794. {
  795. $this->raiseEvent('onAfterDelete',$event);
  796. }
  797. /**
  798. * This event is raised before an AR finder performs a find call.
  799. * In this event, the {@link CModelEvent::criteria} property contains the query criteria
  800. * passed as parameters to those find methods. If you want to access
  801. * the query criteria specified in scopes, please use {@link getDbCriteria()}.
  802. * You can modify either criteria to customize them based on needs.
  803. * @param CModelEvent $event the event parameter
  804. * @see beforeFind
  805. */
  806. public function onBeforeFind($event)
  807. {
  808. $this->raiseEvent('onBeforeFind',$event);
  809. }
  810. /**
  811. * This event is raised after the record is instantiated by a find method.
  812. * @param CEvent $event the event parameter
  813. */
  814. public function onAfterFind($event)
  815. {
  816. $this->raiseEvent('onAfterFind',$event);
  817. }
  818. /**
  819. * This method is invoked before saving a record (after validation, if any).
  820. * The default implementation raises the {@link onBeforeSave} event.
  821. * You may override this method to do any preparation work for record saving.
  822. * Use {@link isNewRecord} to determine whether the saving is
  823. * for inserting or updating record.
  824. * Make sure you call the parent implementation so that the event is raised properly.
  825. * @return boolean whether the saving should be executed. Defaults to true.
  826. */
  827. protected function beforeSave()
  828. {
  829. if($this->hasEventHandler('onBeforeSave'))
  830. {
  831. $event=new CModelEvent($this);
  832. $this->onBeforeSave($event);
  833. return $event->isValid;
  834. }
  835. else
  836. return true;
  837. }
  838. /**
  839. * This method is invoked after saving a record successfully.
  840. * The default implementation raises the {@link onAfterSave} event.
  841. * You may override this method to do postprocessing after record saving.
  842. * Make sure you call the parent implementation so that the event is raised properly.
  843. */
  844. protected function afterSave()
  845. {
  846. if($this->hasEventHandler('onAfterSave'))
  847. $this->onAfterSave(new CEvent($this));
  848. }
  849. /**
  850. * This method is invoked before deleting a record.
  851. * The default implementation raises the {@link onBeforeDelete} event.
  852. * You may override this method to do any preparation work for record deletion.
  853. * Make sure you call the parent implementation so that the event is raised properly.
  854. * @return boolean whether the record should be deleted. Defaults to true.
  855. */
  856. protected function beforeDelete()
  857. {
  858. if($this->hasEventHandler('onBeforeDelete'))
  859. {
  860. $event=new CModelEvent($this);
  861. $this->onBeforeDelete($event);
  862. return $event->isValid;
  863. }
  864. else
  865. return true;
  866. }
  867. /**
  868. * This method is invoked after deleting a record.
  869. * The default implementation raises the {@link onAfterDelete} event.
  870. * You may override this method to do postprocessing after the record is deleted.
  871. * Make sure you call the parent implementation so that the event is raised properly.
  872. */
  873. protected function afterDelete()
  874. {
  875. if($this->hasEventHandler('onAfterDelete'))
  876. $this->onAfterDelete(new CEvent($this));
  877. }
  878. /**
  879. * This method is invoked before an AR finder executes a find call.
  880. * The find calls include {@link find}, {@link findAll}, {@link findByPk},
  881. * {@link findAllByPk}, {@link findByAttributes} and {@link findAllByAttributes}.
  882. * The default implementation raises the {@link onBeforeFind} event.
  883. * If you override this method, make sure you call the parent implementation
  884. * so that the event is raised properly.
  885. */
  886. protected function beforeFind()
  887. {
  888. if($this->hasEventHandler('onBeforeFind'))
  889. {
  890. $event=new CModelEvent($this);
  891. $this->onBeforeFind($event);
  892. }
  893. }
  894. /**
  895. * This method is invoked after each record is instantiated by a find method.
  896. * The default implementation raises the {@link onAfterFind} event.
  897. * You may override this method to do postprocessing after each newly found record is instantiated.
  898. * Make sure you call the parent implementation so that the event is raised properly.
  899. */
  900. protected function afterFind()
  901. {
  902. if($this->hasEventHandler('onAfterFind'))
  903. $this->onAfterFind(new CEvent($this));
  904. }
  905. /**
  906. * Calls {@link beforeFind}.
  907. * This method is internally used.
  908. */
  909. public function beforeFindInternal()
  910. {
  911. $this->beforeFind();
  912. }
  913. /**
  914. * Calls {@link afterFind}.
  915. * This method is internally used.
  916. */
  917. public function afterFindInternal()
  918. {
  919. $this->afterFind();
  920. }
  921. /**
  922. * Inserts a row into the table based on this active record attributes.
  923. * If the table's primary key is auto-incremental and is null before insertion,
  924. * it will be populated with the actual value after insertion.
  925. * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
  926. * After the record is inserted to DB successfully, its {@link isNewRecord} property will be set false,
  927. * and its {@link scenario} property will be set to be 'update'.
  928. * @param array $attributes list of attributes that need to be saved. Defaults to null,
  929. * meaning all attributes that are loaded from DB will be saved.
  930. * @return boolean whether the attributes are valid and the record is inserted successfully.
  931. * @throws CException if the record is not new
  932. */
  933. public function insert($attributes=null)
  934. {
  935. if(!$this->getIsNewRecord())
  936. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  937. if($this->beforeSave())
  938. {
  939. Yii::trace(get_class($this).'.insert()','system.db.ar.CActiveRecord');
  940. $builder=$this->getCommandBuilder();
  941. $table=$this->getMetaData()->tableSchema;
  942. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  943. if($command->execute())
  944. {
  945. $primaryKey=$table->primaryKey;
  946. if($table->sequenceName!==null)
  947. {
  948. if(is_string($primaryKey) && $this->$primaryKey===null)
  949. $this->$primaryKey=$builder->getLastInsertID($table);
  950. else if(is_array($primaryKey))
  951. {
  952. foreach($primaryKey as $pk)
  953. {
  954. if($this->$pk===null)
  955. {
  956. $this->$pk=$builder->getLastInsertID($table);
  957. break;
  958. }
  959. }
  960. }
  961. }
  962. $this->_pk=$this->getPrimaryKey();
  963. $this->afterSave();
  964. $this->setIsNewRecord(false);
  965. $this->setScenario('update');
  966. return true;
  967. }
  968. }
  969. return false;
  970. }
  971. /**
  972. * Updates the row represented by this active record.
  973. * All loaded attributes will be saved to the database.
  974. * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
  975. * @param array $attributes list of attributes that need to be saved. Defaults to null,
  976. * meaning all attributes that are loaded from DB will be saved.
  977. * @return boolean whether the update is successful
  978. * @throws CException if the record is new
  979. */
  980. public function update($attributes=null)
  981. {
  982. if($this->getIsNewRecord())
  983. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  984. if($this->beforeSave())
  985. {
  986. Yii::trace(get_class($this).'.update()','system.db.ar.CActiveRecord');
  987. if($this->_pk===null)
  988. $this->_pk=$this->getPrimaryKey();
  989. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  990. $this->_pk=$this->getPrimaryKey();
  991. $this->afterSave();
  992. return true;
  993. }
  994. else
  995. return false;
  996. }
  997. /**
  998. * Saves a selected list of attributes.
  999. * Unlike {@link save}, this method only saves the specified attributes
  1000. * of an existing row dataset and does NOT call either {@link beforeSave} or {@link afterSave}.
  1001. * Also note that this method does neither attribute filtering nor validation.
  1002. * So do not use this method with untrusted data (such as user posted data).
  1003. * You may consider the following alternative if you want to do so:
  1004. * <pre>
  1005. * $postRecord=Post::model()->findByPk($postID);
  1006. * $postRecord->attributes=$_POST['post'];
  1007. * $postRecord->save();
  1008. * </pre>
  1009. * @param array $attributes attributes to be updated. Each element represents an attribute name
  1010. * or an attribute value indexed by its name. If the latter, the record's
  1011. * attribute will be changed accordingly before saving.
  1012. * @return boolean whether the update is successful
  1013. * @throws CException if the record is new or any database error
  1014. */
  1015. public function saveAttributes($attributes)
  1016. {
  1017. if(!$this->getIsNewRecord())
  1018. {
  1019. Yii::trace(get_class($this).'.saveAttributes()','system.db.ar.CActiveRecord');
  1020. $values=array();
  1021. foreach($attributes as $name=>$value)
  1022. {
  1023. if(is_integer($name))
  1024. $values[$value]=$this->$value;
  1025. else
  1026. $values[$name]=$this->$name=$value;
  1027. }
  1028. if($this->_pk===null)
  1029. $this->_pk=$this->getPrimaryKey();
  1030. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  1031. {
  1032. $this->_pk=$this->getPrimaryKey();
  1033. return true;
  1034. }
  1035. else
  1036. return false;
  1037. }
  1038. else
  1039. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  1040. }
  1041. /**
  1042. * Saves one or several counter columns for the current AR object.
  1043. * Note that this method differs from {@link updateCounters} in that it only
  1044. * saves the current AR object.
  1045. * An example usage is as follows:
  1046. * <pre>
  1047. * $postRecord=Post::model()->findByPk($postID);
  1048. * $postRecord->saveCounters(array('view_count'=>1));
  1049. * </pre>
  1050. * Use negative values if you want to decrease the counters.
  1051. * @param array $counters the counters to be updated (column name=>increment value)
  1052. * @return boolean whether the saving is successful
  1053. * @see updateCounters
  1054. * @since 1.1.8
  1055. */
  1056. public function saveCounters($counters)
  1057. {
  1058. Yii::trace(get_class($this).'.saveCounters()','system.db.ar.CActiveRecord');
  1059. $builder=$this->getCommandBuilder();
  1060. $table=$this->getTableSchema();
  1061. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  1062. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  1063. if($command->execute())
  1064. {
  1065. foreach($counters as $name=>$value)
  1066. $this->$name=$this->$name+$value;
  1067. return true;
  1068. }
  1069. else
  1070. return false;
  1071. }
  1072. /**
  1073. * Deletes the row corresponding to this active record.
  1074. * @return boolean whether the deletion is successful.
  1075. * @throws CException if the record is new
  1076. */
  1077. public function delete()
  1078. {
  1079. if(!$this->getIsNewRecord())
  1080. {
  1081. Yii::trace(get_class($this).'.delete()','system.db.ar.CActiveRecord');
  1082. if($this->beforeDelete())
  1083. {
  1084. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  1085. $this->afterDelete();
  1086. return $result;
  1087. }
  1088. else
  1089. return false;
  1090. }
  1091. else
  1092. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  1093. }
  1094. /**
  1095. * Repopulates this active record with the latest data.
  1096. * @return boolean whether the row still exists in the database. If true, the latest data will be populated to this active record.
  1097. */
  1098. public function refresh()
  1099. {
  1100. Yii::trace(get_class($this).'.refresh()','system.db.ar.CActiveRecord');
  1101. if(($record=$this->findByPk($this->getPrimaryKey()))!==null)
  1102. {
  1103. $this->_attributes=array();
  1104. $this->_related=array();
  1105. foreach($this->getMetaData()->columns as $name=>$column)
  1106. {
  1107. if(property_exists($this,$name))
  1108. $this->$name=$record->$name;
  1109. else
  1110. $this->_attributes[$name]=$record->$name;
  1111. }
  1112. return true;
  1113. }
  1114. else
  1115. return false;
  1116. }
  1117. /**
  1118. * Compares current active record with another one.
  1119. * The comparison is made by comparing table name and the primary key values of the two active records.
  1120. * @param CActiveRecord $record record to compare to
  1121. * @return boolean whether the two active records refer to the same row in the database table.
  1122. */
  1123. public function equals($record)
  1124. {
  1125. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  1126. }
  1127. /**
  1128. * Returns the primary key value.
  1129. * @return mixed the primary key value. An array (column name=>column value) is returned if the primary key is composite.
  1130. * If primary key is not defined, null will be returned.
  1131. */
  1132. public function getPrimaryKey()
  1133. {
  1134. $table=$this->getMetaData()->tableSchema;
  1135. if(is_string($table->primaryKey))
  1136. return $this->{$table->primaryKey};
  1137. else if(is_array($table->primaryKey))
  1138. {
  1139. $values=array();
  1140. foreach($table->primaryKey as $name)
  1141. $values[$name]=$this->$name;
  1142. return $values;
  1143. }
  1144. else
  1145. return null;
  1146. }
  1147. /**
  1148. * Sets the primary key value.
  1149. * After calling this method, the old primary key value can be obtained from {@link oldPrimaryKey}.
  1150. * @param mixed $value the new primary key value. If the primary key is composite, the new value
  1151. * should be provided as an array (column name=>column value).
  1152. * @since 1.1.0
  1153. */
  1154. public function setPrimaryKey($value)
  1155. {
  1156. $this->_pk=$this->getPrimaryKey();
  1157. $table=$this->getMetaData()->tableSchema;
  1158. if(is_string($table->primaryKey))
  1159. $this->{$table->primaryKey}=$value;
  1160. else if(is_array($table->primaryKey))
  1161. {
  1162. foreach($table->primaryKey as $name)
  1163. $this->$name=$value[$name];
  1164. }
  1165. }
  1166. /**
  1167. * Returns the old primary key value.
  1168. * This refers to the primary key value that is populated into the record
  1169. * after executing a find method (e.g. find(), findAll()).
  1170. * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
  1171. * @return mixed the old primary key value. An array (column name=>column value) is returned if the primary key is composite.
  1172. * If primary key is not defined, null will be returned.
  1173. * @since 1.1.0
  1174. */
  1175. public function getOldPrimaryKey()
  1176. {
  1177. return $this->_pk;
  1178. }
  1179. /**
  1180. * Sets the old primary key value.
  1181. * @param mixed $value the old primary key value.
  1182. * @since 1.1.3
  1183. */
  1184. public function setOldPrimaryKey($value)
  1185. {
  1186. $this->_pk=$value;
  1187. }
  1188. /**
  1189. * Performs the actual DB query and populates the AR objects with the query result.
  1190. * This method is mainly internally used by other AR query methods.
  1191. * @param CDbCriteria $criteria the query criteria
  1192. * @param boolean $all whether to return all data
  1193. * @return mixed the AR objects populated with the query result
  1194. * @since 1.1.7
  1195. */
  1196. protected function query($criteria,$all=false)
  1197. {
  1198. $this->beforeFind();
  1199. $this->applyScopes($criteria);
  1200. if(empty($criteria->with))
  1201. {
  1202. if(!$all)
  1203. $criteria->limit=1;
  1204. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  1205. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  1206. }
  1207. else
  1208. {
  1209. $finder=new CActiveFinder($this,$criteria->with);
  1210. return $finder->query($criteria,$all);
  1211. }
  1212. }
  1213. /**
  1214. * Applies the query scopes to the given criteria.
  1215. * This method merges {@link dbCriteria} with the given criteria parameter.
  1216. * It then resets {@link dbCriteria} to be null.
  1217. * @param CDbCriteria $criteria the query criteria. This parameter may be modified by merging {@link dbCriteria}.
  1218. */
  1219. public function applyScopes(&$criteria)
  1220. {
  1221. if(!empty($criteria->scopes))
  1222. {
  1223. $scs=$this->scopes();
  1224. $c=$this->getDbCriteria();
  1225. foreach((array)$criteria->scopes as $k=>$v)
  1226. {
  1227. if(is_integer($k))
  1228. {
  1229. if(is_string($v))
  1230. {
  1231. if(isset($scs[$v]))
  1232. {
  1233. $c->mergeWith($scs[$v],true);
  1234. continue;
  1235. }
  1236. $scope=$v;
  1237. $params=array();
  1238. }
  1239. else if(is_array($v))
  1240. {
  1241. $scope=key($v);
  1242. $params=current($v);
  1243. }
  1244. }
  1245. else if(is_string($k))
  1246. {
  1247. $scope=$k;
  1248. $params=$v;
  1249. }
  1250. call_user_func_array(array($this,$scope),(array)$params);
  1251. }
  1252. }
  1253. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  1254. {
  1255. $c->mergeWith($criteria);
  1256. $criteria=$c;
  1257. $this->_c=null;
  1258. }
  1259. }
  1260. /**
  1261. * Returns the table alias to be used by the find methods.
  1262. * In relational queries, the returned table alias may vary according to
  1263. * the corresponding relation declaration. Also, the default table alias
  1264. * set by {@link setTableAlias} may be overridden by the applied scopes.
  1265. * @param boolean $quote whether to quote the alias name
  1266. * @param boolean $checkScopes whether to check if a table alias is defined in the applied scopes so far.
  1267. * This parameter must be set false when calling this method in {@link defaultScope}.
  1268. * An infinite loop would be formed otherwise.
  1269. * @return string the default table alias
  1270. * @since 1.1.1
  1271. */
  1272. public function getTableAlias($quote=false, $checkScopes=true)
  1273. {
  1274. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  1275. $alias=$criteria->alias;
  1276. else
  1277. $alias=$this->_alias;
  1278. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  1279. }
  1280. /**
  1281. * Sets the table alias to be used in queries.
  1282. * @param string $alias the table alias to be used in queries. The alias should NOT be quoted.
  1283. * @since 1.1.3
  1284. */
  1285. public function setTableAlias($alias)
  1286. {
  1287. $this->_alias=$alias;
  1288. }
  1289. /**
  1290. * Finds a single active record with the specified condition.
  1291. * @param mixed $condition query condition or criteria.
  1292. * If a string, it is treated as query condition (the WHERE clause);
  1293. * If an array, it is treated as the initial values for constructing a {@link CDbCriteria} object;
  1294. * Otherwise, it should be an instance of {@link CDbCriteria}.
  1295. * @param array $params parameters to be bound to an SQL statement.
  1296. * This is only used when the first parameter is a string (query condition).
  1297. * In other cases, please use {@link CDbCriteria::params} to set parameters.
  1298. * @return CActiveRecord the record found. Null if no record is found.
  1299. */
  1300. public function find($condition='',$params=array())
  1301. {
  1302. Yii::trace(get_class($this).'.find()','system.db.ar.CActiveRecord');
  1303. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  1304. return $this->query($criteria);
  1305. }
  1306. /**
  1307. * Finds all active records satisfying the specified condition.
  1308. * See {@link find()} for detailed explanation about $condition and $params.
  1309. * @param mixed $condition query condition or criteria.
  1310. * @param array $params parameters to be bound to an SQL statement.
  1311. * @return array list of active records satisfying the specified condition. An empty array is returned if none is found.
  1312. */
  1313. public function findAll($condition='',$params=array())
  1314. {
  1315. Yii::trace(get_class($this).'.findAll()','system.db.ar.CActiveRecord');
  1316. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  1317. return $this->query($criteria,true);
  1318. }
  1319. /**
  1320. * Finds a single active record with the specified primary key.
  1321. * See {@link find()} for detailed explanation about $condition and $params.
  1322. * @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
  1323. * @param mixed $condition query condition or criteria.
  1324. * @param array $params parameters to be bound to an SQL statement.
  1325. * @return CActiveRecord the record found. Null if none is found.
  1326. */
  1327. public function findByPk($pk,$condition='',$params=array())
  1328. {
  1329. Yii::trace(get_class($this).'.findByPk()','system.db.ar.CActiveRecord');
  1330. $prefix=$this->getTableAlias(true).'.';
  1331. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  1332. return $this->query($criteria);
  1333. }
  1334. /**
  1335. * Finds all active records with the specified primary keys.
  1336. * See {@link find()} for detailed explanation about $condition and $params.
  1337. * @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
  1338. * @param mixed $condition query condition or criteria.
  1339. * @param array $params parameters to be bound to an SQL statement.
  1340. * @return array the records found. An empty array is returned if none is found.
  1341. */
  1342. public function findAllByPk($pk,$condition='',$params=array())
  1343. {
  1344. Yii::trace(get_class($this).'.findAllByPk()','system.db.ar.CActiveRecord');
  1345. $prefix=$this->getTableAlias(true).'.';
  1346. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  1347. return $this->query($criteria,true);
  1348. }
  1349. /**
  1350. * Finds a single active record that has the specified attribute values.
  1351. * See {@link find()} for detailed explanation about $condition and $params.
  1352. * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match.
  1353. * An attribute value can be an array which will be used to generate an IN condition.
  1354. * @param mixed $condition query condition or criteria.
  1355. * @param array $params parameters to be bound to an SQL statement.
  1356. * @return CActiveRecord the record found. Null if none is found.
  1357. */
  1358. public function findByAttributes($attributes,$condition='',$params=array())
  1359. {
  1360. Yii::trace(get_class($this).'.findByAttributes()','system.db.ar.CActiveRecord');
  1361. $prefix=$this->getTableAlias(true).'.';
  1362. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  1363. return $this->query($criteria);
  1364. }
  1365. /**
  1366. * Finds all active records that have the specified attribute values.
  1367. * See {@link find()} for detailed explanation about $condition and $params.
  1368. * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match.
  1369. * An attribute value can be an array which will be used to generate an IN condition.
  1370. * @param mixed $condition query condition or criteria.
  1371. * @param array $params parameters to be bound to an SQL statement.
  1372. * @return array the records found. An empty array is returned if none is found.
  1373. */
  1374. public function findAllByAttributes($attributes,$condition='',$params=array())
  1375. {
  1376. Yii::trace(get_class($this).'.findAllByAttributes()','system.db.ar.CActiveRecord');
  1377. $prefix=$this->getTableAlias(true).'.';
  1378. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  1379. return $this->query($criteria,true);
  1380. }
  1381. /**
  1382. * Finds a single active record with the specified SQL statement.
  1383. * @param string $sql the SQL statement
  1384. * @param array $params parameters to be bound to the SQL statement
  1385. * @return CActiveRecord the record found. Null if none is found.
  1386. */
  1387. public function findBySql($sql,$params=array())
  1388. {
  1389. Yii::trace(get_class($this).'.findBySql()','system.db.ar.CActiveRecord');
  1390. $this->beforeFind();
  1391. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  1392. {
  1393. $this->_c=null;
  1394. $finder=new CActiveFinder($this,$criteria->with);
  1395. return $finder->findBySql($sql,$params);
  1396. }
  1397. else
  1398. {
  1399. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  1400. return $this->populateRecord($command->queryRow());
  1401. }
  1402. }
  1403. /**
  1404. * Finds all active records using the specified SQL statement.
  1405. * @param string $sql the SQL statement
  1406. * @param array $params parameters to be bound to the SQL statement
  1407. * @return array the records found. An empty array is returned if none is found.
  1408. */
  1409. public function findAllBySql($sql,$params=array())
  1410. {
  1411. Yii::trace(get_class($this).'.findAllBySql()','system.db.ar.CActiveRecord');
  1412. $this->beforeFind();
  1413. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  1414. {
  1415. $this->_c=null;
  1416. $finder=new CActiveFinder($this,$criteria->with);
  1417. return $finder->findAllBySql($sql,$params);
  1418. }
  1419. else
  1420. {
  1421. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  1422. return $this->populateRecords($command->queryAll());
  1423. }
  1424. }
  1425. /**
  1426. * Finds the number of rows satisfying the specified query condition.
  1427. * See {@link find()} for detailed explanation about $condition and $params.
  1428. * @param mixed $condition query condition or criteria.
  1429. * @param array $params parameters to be bound to an SQL statement.
  1430. * @return string the number of rows satisfying the specified query condition. Note: type is string to keep max. precision.
  1431. */
  1432. public function count($condition='',$params=array())
  1433. {
  1434. Yii::trace(get_class($this).'.count()','system.db.ar.CActiveRecord');
  1435. $builder=$this->getCommandBuilder();
  1436. $criteria=$builder->createCriteria($condition,$params);
  1437. $this->applyScopes($criteria);
  1438. if(empty($criteria->with))
  1439. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  1440. else
  1441. {
  1442. $finder=new CActiveFinder($this,$criteria->with);
  1443. return $finder->count($criteria);
  1444. }
  1445. }
  1446. /**
  1447. * Finds the number of rows that have the specified attribute values.
  1448. * See {@link find()} for detailed explanation about $condition and $params.
  1449. * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match.
  1450. * An attribute value can be an array which will be used to generate an IN condition.
  1451. * @param mixed $condition query condition or criteria.
  1452. * @param array $params parameters to be bound to an SQL statement.
  1453. * @return string the number of rows satisfying the specified query condition. Note: type is string to keep max. precision.
  1454. * @since 1.1.4
  1455. */
  1456. public function countByAttributes($attributes,$condition='',$params=array())
  1457. {
  1458. Yii::trace(get_class($this).'.countByAttributes()','system.db.ar.CActiveRecord');
  1459. $prefix=$this->getTableAlias(true).'.';
  1460. $builder=$this->getCommandBuilder();
  1461. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  1462. $this->applyScopes($criteria);
  1463. if(empty($criteria->with))
  1464. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  1465. else
  1466. {
  1467. $finder=new CActiveFinder($this,$criteria->with);
  1468. return $finder->count($criteria);
  1469. }
  1470. }
  1471. /**
  1472. * Finds the number of rows using the given SQL statement.
  1473. * This is equivalent to calling {@link CDbCommand::queryScalar} with the specified
  1474. * SQL statement and the parameters.
  1475. * @param string $sql the SQL statement
  1476. * @param array $params parameters to be bound to the SQL statement
  1477. * @return string the number of rows using the given SQL statement. Note: type is string to keep max. precision.
  1478. */
  1479. public function countBySql($sql,$params=array())
  1480. {
  1481. Yii::trace(get_class($this).'.countBySql()','system.db.ar.CActiveRecord');
  1482. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  1483. }
  1484. /**
  1485. * Checks whether there is row satisfying the specified condition.
  1486. * See {@link find()} for detailed explanation about $condition and $params.
  1487. * @param mixed $condition query condition or criteria.
  1488. * @param array $params parameters to be bound to an SQL statement.
  1489. * @return boolean whether there is row satisfying the specified condition.
  1490. */
  1491. public function exists($condition='',$params=array())
  1492. {
  1493. Yii::trace(get_class($this).'.exists()','system.db.ar.CActiveRecord');
  1494. $builder=$this->getCommandBuilder();
  1495. $criteria=$builder->createCriteria($condition,$params);
  1496. $table=$this->getTableSchema();
  1497. $criteria->select='1';
  1498. $criteria->limit=1;
  1499. $this->applyScopes($criteria);
  1500. if(empty($criteria->with))
  1501. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  1502. else
  1503. {
  1504. $criteria->select='*';
  1505. $finder=new CActiveFinder($this,$criteria->with);
  1506. return $finder->count($criteria)>0;
  1507. }
  1508. }
  1509. /**
  1510. * Specifies which related objects should be eagerly loaded.
  1511. * This method takes variable number of parameters. Each parameter specifies
  1512. * the name of a relation or child-relation. For example,
  1513. * <pre>
  1514. * // find all posts together with their author and comments
  1515. * Post::model()->with('author','comments')->findAll();
  1516. * // find all posts together with their author and the author's profile
  1517. * Post::model()->with('author','author.profile')->findAll();
  1518. * </pre>
  1519. * The relations should be declared in {@link relations()}.
  1520. *
  1521. * By default, the options specified in {@link relations()} will be used
  1522. * to do relational query. In order to customize the options on the fly,
  1523. * we should pass an array parameter to the with() method. The array keys
  1524. * are relation names, and the array values are the corresponding query options.
  1525. * For example,
  1526. * <pre>
  1527. * Post::model()->with(array(
  1528. * 'author'=>array('select'=>'id, name'),
  1529. * 'comments'=>array('condition'=>'approved=1', 'order'=>'create_time'),
  1530. * ))->findAll();
  1531. * </pre>
  1532. *
  1533. * @return CActiveRecord the AR object itself.
  1534. */
  1535. public function with()
  1536. {
  1537. if(func_num_args()>0)
  1538. {
  1539. $with=func_get_args();
  1540. if(is_array($with[0])) // the parameter is given as an array
  1541. $with=$with[0];
  1542. if(!empty($with))
  1543. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  1544. }
  1545. return $this;
  1546. }
  1547. /**
  1548. * Sets {@link CDbCriteria::together} property to be true.
  1549. * This is only used in relational AR query. Please refer to {@link CDbCriteria::together}
  1550. * for more details.
  1551. * @return CActiveRecord the AR object itself
  1552. * @since 1.1.4
  1553. */
  1554. public function together()
  1555. {
  1556. $this->getDbCriteria()->together=true;
  1557. return $this;
  1558. }
  1559. /**
  1560. * Updates records with the specified primary key(s).
  1561. * See {@link find()} for detailed explanation about $condition and $params.
  1562. * Note, the attributes are not checked for safety and validation is NOT performed.
  1563. * @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
  1564. * @param array $attributes list of attributes (name=>$value) to be updated
  1565. * @param mixed $condition query condition or criteria.
  1566. * @param array $params parameters to be bound to an SQL statement.
  1567. * @return integer the number of rows being updated
  1568. */
  1569. public function updateByPk($pk,$attributes,$condition='',$params=array())
  1570. {
  1571. Yii::trace(get_class($this).'.updateByPk()','system.db.ar.CActiveRecord');
  1572. $builder=$this->getCommandBuilder();
  1573. $table=$this->getTableSchema();
  1574. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  1575. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  1576. return $command->execute();
  1577. }
  1578. /**
  1579. * Updates records with the specified condition.
  1580. * See {@link find()} for detailed explanation about $condition and $params.
  1581. * Note, the attributes are not checked for safety and no validation is done.
  1582. * @param array $attributes list of attributes (name=>$value) to be updated
  1583. * @param mixed $condition query condition or criteria.
  1584. * @param array $params parameters to be bound to an SQL statement.
  1585. * @return integer the number of rows being updated
  1586. */
  1587. public function updateAll($attributes,$condition='',$params=array())
  1588. {
  1589. Yii::trace(get_class($this).'.updateAll()','system.db.ar.CActiveRecord');
  1590. $builder=$this->getCommandBuilder();
  1591. $criteria=$builder->createCriteria($condition,$params);
  1592. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  1593. return $command->execute();
  1594. }
  1595. /**
  1596. * Updates one or several counter columns.
  1597. * Note, this updates all rows of data unless a condition or criteria is specified.
  1598. * See {@link find()} for detailed explanation about $condition and $params.
  1599. * @param array $counters the counters to be updated (column name=>increment value)
  1600. * @param mixed $condition query condition or criteria.
  1601. * @param array $params parameters to be bound to an SQL statement.
  1602. * @return integer the number of rows being updated
  1603. * @see saveCounters
  1604. */
  1605. public function updateCounters($counters,$condition='',$params=array())
  1606. {
  1607. Yii::trace(get_class($this).'.updateCounters()','system.db.ar.CActiveRecord');
  1608. $builder=$this->getCommandBuilder();
  1609. $criteria=$builder->createCriteria($condition,$params);
  1610. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  1611. return $command->execute();
  1612. }
  1613. /**
  1614. * Deletes rows with the specified primary key.
  1615. * See {@link find()} for detailed explanation about $condition and $params.
  1616. * @param mixed $pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
  1617. * @param mixed $condition query condition or criteria.
  1618. * @param array $params parameters to be bound to an SQL statement.
  1619. * @return integer the number of rows deleted
  1620. */
  1621. public function deleteByPk($pk,$condition='',$params=array())
  1622. {
  1623. Yii::trace(get_class($this).'.deleteByPk()','system.db.ar.CActiveRecord');
  1624. $builder=$this->getCommandBuilder();
  1625. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  1626. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  1627. return $command->execute();
  1628. }
  1629. /**
  1630. * Deletes rows with the specified condition.
  1631. * See {@link find()} for detailed explanation about $condition and $params.
  1632. * @param mixed $condition query condition or criteria.
  1633. * @param array $params parameters to be bound to an SQL statement.
  1634. * @return integer the number of rows deleted
  1635. */
  1636. public function deleteAll($condition='',$params=array())
  1637. {
  1638. Yii::trace(get_class($this).'.deleteAll()','system.db.ar.CActiveRecord');
  1639. $builder=$this->getCommandBuilder();
  1640. $criteria=$builder->createCriteria($condition,$params);
  1641. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  1642. return $command->execute();
  1643. }
  1644. /**
  1645. * Deletes rows which match the specified attribute values.
  1646. * See {@link find()} for detailed explanation about $condition and $params.
  1647. * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match.
  1648. * An attribute value can be an array which will be used to generate an IN condition.
  1649. * @param mixed $condition query condition or criteria.
  1650. * @param array $params parameters to be bound to an SQL statement.
  1651. * @return integer number of rows affected by the execution.
  1652. */
  1653. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  1654. {
  1655. Yii::trace(get_class($this).'.deleteAllByAttributes()','system.db.ar.CActiveRecord');
  1656. $builder=$this->getCommandBuilder();
  1657. $table=$this->getTableSchema();
  1658. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  1659. $command=$builder->createDeleteCommand($table,$criteria);
  1660. return $command->execute();
  1661. }
  1662. /**
  1663. * Creates an active record with the given attributes.
  1664. * This method is internally used by the find methods.
  1665. * @param array $attributes attribute values (column name=>column value)
  1666. * @param boolean $callAfterFind whether to call {@link afterFind} after the record is populated.
  1667. * @return CActiveRecord the newly created active record. The class of the object is the same as the model class.
  1668. * Null is returned if the input data is false.
  1669. */
  1670. public function populateRecord($attributes,$callAfterFind=true)
  1671. {
  1672. if($attributes!==false)
  1673. {
  1674. $record=$this->instantiate($attributes);
  1675. $record->setScenario('update');
  1676. $record->init();
  1677. $md=$record->getMetaData();
  1678. foreach($attributes as $name=>$value)
  1679. {
  1680. if(property_exists($record,$name))
  1681. $record->$name=$value;
  1682. else if(isset($md->columns[$name]))
  1683. $record->_attributes[$name]=$value;
  1684. }
  1685. $record->_pk=$record->getPrimaryKey();
  1686. $record->attachBehaviors($record->behaviors());
  1687. if($callAfterFind)
  1688. $record->afterFind();
  1689. return $record;
  1690. }
  1691. else
  1692. return null;
  1693. }
  1694. /**
  1695. * Creates a list of active records based on the input data.
  1696. * This method is internally used by the find methods.
  1697. * @param array $data list of attribute values for the active records.
  1698. * @param boolean $callAfterFind whether to call {@link afterFind} after each record is populated.
  1699. * @param string $index the name of the attribute whose value will be used as indexes of the query result array.
  1700. * If null, it means the array will be indexed by zero-based integers.
  1701. * @return array list of active records.
  1702. */
  1703. public function populateRecords($data,$callAfterFind=true,$index=null)
  1704. {
  1705. $records=array();
  1706. foreach($data as $attributes)
  1707. {
  1708. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  1709. {
  1710. if($index===null)
  1711. $records[]=$record;
  1712. else
  1713. $records[$record->$index]=$record;
  1714. }
  1715. }
  1716. return $records;
  1717. }
  1718. /**
  1719. * Creates an active record instance.
  1720. * This method is called by {@link populateRecord} and {@link populateRecords}.
  1721. * You may override this method if the instance being created
  1722. * depends the attributes that are to be populated to the record.
  1723. * For example, by creating a record based on the value of a column,
  1724. * you may implement the so-called single-table inheritance mapping.
  1725. * @param array $attributes list of attribute values for the active records.
  1726. * @return CActiveRecord the active record
  1727. */
  1728. protected function instantiate($attributes)
  1729. {
  1730. $class=get_class($this);
  1731. $model=new $class(null);
  1732. return $model;
  1733. }
  1734. /**
  1735. * Returns whether there is an element at the specified offset.
  1736. * This method is required by the interface ArrayAccess.
  1737. * @param mixed $offset the offset to check on
  1738. * @return boolean
  1739. */
  1740. public function offsetExists($offset)
  1741. {
  1742. return $this->__isset($offset);
  1743. }
  1744. }
  1745. /**
  1746. * CBaseActiveRelation is the base class for all active relations.
  1747. * @author Qiang Xue <qiang.xue@gmail.com>
  1748. * @version $Id$
  1749. * @package system.db.ar
  1750. */
  1751. class CBaseActiveRelation extends CComponent
  1752. {
  1753. /**
  1754. * @var string name of the related object
  1755. */
  1756. public $name;
  1757. /**
  1758. * @var string name of the related active record class
  1759. */
  1760. public $className;
  1761. /**
  1762. * @var mixed the foreign key in this relation
  1763. */
  1764. public $foreignKey;
  1765. /**
  1766. * @var mixed list of column names (an array, or a string of names separated by commas) to be selected.
  1767. * Do not quote or prefix the column names unless they are used in an expression.
  1768. * In that case, you should prefix the column names with 'relationName.'.
  1769. */
  1770. public $select='*';
  1771. /**
  1772. * @var string WHERE clause. For {@link CActiveRelation} descendant classes, column names
  1773. * referenced in the condition should be disambiguated with prefix 'relationName.'.
  1774. */
  1775. public $condition='';
  1776. /**
  1777. * @var array the parameters that are to be bound to the condition.
  1778. * The keys are parameter placeholder names, and the values are parameter values.
  1779. */
  1780. public $params=array();
  1781. /**
  1782. * @var string GROUP BY clause. For {@link CActiveRelation} descendant classes, column names
  1783. * referenced in this property should be disambiguated with prefix 'relationName.'.
  1784. */
  1785. public $group='';
  1786. /**
  1787. * @var string how to join with other tables. This refers to the JOIN clause in an SQL statement.
  1788. * For example, <code>'LEFT JOIN users ON users.id=authorID'</code>.
  1789. * @since 1.1.3
  1790. */
  1791. public $join='';
  1792. /**
  1793. * @var string HAVING clause. For {@link CActiveRelation} descendant classes, column names
  1794. * referenced in this property should be disambiguated with prefix 'relationName.'.
  1795. */
  1796. public $having='';
  1797. /**
  1798. * @var string ORDER BY clause. For {@link CActiveRelation} descendant classes, column names
  1799. * referenced in this property should be disambiguated with prefix 'relationName.'.
  1800. */
  1801. public $order='';
  1802. /**
  1803. * Constructor.
  1804. * @param string $name name of the relation
  1805. * @param string $className name of the related active record class
  1806. * @param string $foreignKey foreign key for this relation
  1807. * @param array $options additional options (name=>value). The keys must be the property names of this class.
  1808. */
  1809. public function __construct($name,$className,$foreignKey,$options=array())
  1810. {
  1811. $this->name=$name;
  1812. $this->className=$className;
  1813. $this->foreignKey=$foreignKey;
  1814. foreach($options as $name=>$value)
  1815. $this->$name=$value;
  1816. }
  1817. /**
  1818. * Merges this relation with a criteria specified dynamically.
  1819. * @param array $criteria the dynamically specified criteria
  1820. * @param boolean $fromScope whether the criteria to be merged is from scopes
  1821. */
  1822. public function mergeWith($criteria,$fromScope=false)
  1823. {
  1824. if($criteria instanceof CDbCriteria)
  1825. $criteria=$criteria->toArray();
  1826. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  1827. {
  1828. if($this->select==='*')
  1829. $this->select=$criteria['select'];
  1830. else if($criteria['select']!=='*')
  1831. {
  1832. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  1833. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  1834. $this->select=array_merge($select1,array_diff($select2,$select1));
  1835. }
  1836. }
  1837. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  1838. {
  1839. if($this->condition==='')
  1840. $this->condition=$criteria['condition'];
  1841. else if($criteria['condition']!=='')
  1842. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  1843. }
  1844. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  1845. $this->params=array_merge($this->params,$criteria['params']);
  1846. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  1847. {
  1848. if($this->order==='')
  1849. $this->order=$criteria['order'];
  1850. else if($criteria['order']!=='')
  1851. $this->order=$criteria['order'].', '.$this->order;
  1852. }
  1853. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  1854. {
  1855. if($this->group==='')
  1856. $this->group=$criteria['group'];
  1857. else if($criteria['group']!=='')
  1858. $this->group.=', '.$criteria['group'];
  1859. }
  1860. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  1861. {
  1862. if($this->join==='')
  1863. $this->join=$criteria['join'];
  1864. else if($criteria['join']!=='')
  1865. $this->join.=' '.$criteria['join'];
  1866. }
  1867. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  1868. {
  1869. if($this->having==='')
  1870. $this->having=$criteria['having'];
  1871. else if($criteria['having']!=='')
  1872. $this->having="({$this->having}) AND ({$criteria['having']})";
  1873. }
  1874. }
  1875. }
  1876. /**
  1877. * CStatRelation represents a statistical relational query.
  1878. * @author Qiang Xue <qiang.xue@gmail.com>
  1879. * @version $Id$
  1880. * @package system.db.ar
  1881. */
  1882. class CStatRelation extends CBaseActiveRelation
  1883. {
  1884. /**
  1885. * @var string the statistical expression. Defaults to 'COUNT(*)', meaning
  1886. * the count of child objects.
  1887. */
  1888. public $select='COUNT(*)';
  1889. /**
  1890. * @var mixed the default value to be assigned to those records that do not
  1891. * receive a statistical query result. Defaults to 0.
  1892. */
  1893. public $defaultValue=0;
  1894. /**
  1895. * Merges this relation with a criteria specified dynamically.
  1896. * @param array $criteria the dynamically specified criteria
  1897. * @param boolean $fromScope whether the criteria to be merged is from scopes
  1898. */
  1899. public function mergeWith($criteria,$fromScope=false)
  1900. {
  1901. if($criteria instanceof CDbCriteria)
  1902. $criteria=$criteria->toArray();
  1903. parent::mergeWith($criteria,$fromScope);
  1904. if(isset($criteria['defaultValue']))
  1905. $this->defaultValue=$criteria['defaultValue'];
  1906. }
  1907. }
  1908. /**
  1909. * CActiveRelation is the base class for representing active relations that bring back related objects.
  1910. * @author Qiang Xue <qiang.xue@gmail.com>
  1911. * @version $Id$
  1912. * @package system.db.ar
  1913. * @since 1.0
  1914. */
  1915. class CActiveRelation extends CBaseActiveRelation
  1916. {
  1917. /**
  1918. * @var string join type. Defaults to 'LEFT OUTER JOIN'.
  1919. */
  1920. public $joinType='LEFT OUTER JOIN';
  1921. /**
  1922. * @var string ON clause. The condition specified here will be appended to the joining condition using AND operator.
  1923. */
  1924. public $on='';
  1925. /**
  1926. * @var string the alias for the table that this relation refers to. Defaults to null, meaning
  1927. * the alias will be the same as the relation name.
  1928. */
  1929. public $alias;
  1930. /**
  1931. * @var string|array specifies which related objects should be eagerly loaded when this related object is lazily loaded.
  1932. * For more details about this property, see {@link CActiveRecord::with()}.
  1933. */
  1934. public $with=array();
  1935. /**
  1936. * @var boolean whether this table should be joined with the primary table.
  1937. * When setting this property to be false, the table associated with this relation will
  1938. * appear in a separate JOIN statement.
  1939. * If this property is set true, then the corresponding table will ALWAYS be joined together
  1940. * with the primary table, no matter the primary table is limited or not.
  1941. * If this property is not set, the corresponding table will be joined with the primary table
  1942. * only when the primary table is not limited.
  1943. */
  1944. public $together;
  1945. /**
  1946. * @var mixed scopes to apply
  1947. * Can be set to the one of the following:
  1948. * <ul>
  1949. * <li>Single scope: 'scopes'=>'scopeName'.</li>
  1950. * <li>Multiple scopes: 'scopes'=>array('scopeName1','scopeName2').</li>
  1951. * </ul>
  1952. * @since 1.1.9
  1953. */
  1954. public $scopes;
  1955. /**
  1956. * Merges this relation with a criteria specified dynamically.
  1957. * @param array $criteria the dynamically specified criteria
  1958. * @param boolean $fromScope whether the criteria to be merged is from scopes
  1959. */
  1960. public function mergeWith($criteria,$fromScope=false)
  1961. {
  1962. if($criteria instanceof CDbCriteria)
  1963. $criteria=$criteria->toArray();
  1964. if($fromScope)
  1965. {
  1966. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  1967. {
  1968. if($this->on==='')
  1969. $this->on=$criteria['condition'];
  1970. else if($criteria['condition']!=='')
  1971. $this->on="({$this->on}) AND ({$criteria['condition']})";
  1972. }
  1973. unset($criteria['condition']);
  1974. }
  1975. parent::mergeWith($criteria);
  1976. if(isset($criteria['joinType']))
  1977. $this->joinType=$criteria['joinType'];
  1978. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  1979. {
  1980. if($this->on==='')
  1981. $this->on=$criteria['on'];
  1982. else if($criteria['on']!=='')
  1983. $this->on="({$this->on}) AND ({$criteria['on']})";
  1984. }
  1985. if(isset($criteria['with']))
  1986. $this->with=$criteria['with'];
  1987. if(isset($criteria['alias']))
  1988. $this->alias=$criteria['alias'];
  1989. if(isset($criteria['together']))
  1990. $this->together=$criteria['together'];
  1991. }
  1992. }
  1993. /**
  1994. * CBelongsToRelation represents the parameters specifying a BELONGS_TO relation.
  1995. * @author Qiang Xue <qiang.xue@gmail.com>
  1996. * @version $Id$
  1997. * @package system.db.ar
  1998. * @since 1.0
  1999. */
  2000. class CBelongsToRelation extends CActiveRelation
  2001. {
  2002. }
  2003. /**
  2004. * CHasOneRelation represents the parameters specifying a HAS_ONE relation.
  2005. * @author Qiang Xue <qiang.xue@gmail.com>
  2006. * @version $Id$
  2007. * @package system.db.ar
  2008. * @since 1.0
  2009. */
  2010. class CHasOneRelation extends CActiveRelation
  2011. {
  2012. /**
  2013. * @var string the name of the relation that should be used as the bridge to this relation.
  2014. * Defaults to null, meaning don't use any bridge.
  2015. * @since 1.1.7
  2016. */
  2017. public $through;
  2018. }
  2019. /**
  2020. * CHasManyRelation represents the parameters specifying a HAS_MANY relation.
  2021. * @author Qiang Xue <qiang.xue@gmail.com>
  2022. * @version $Id$
  2023. * @package system.db.ar
  2024. * @since 1.0
  2025. */
  2026. class CHasManyRelation extends CActiveRelation
  2027. {
  2028. /**
  2029. * @var integer limit of the rows to be selected. It is effective only for lazy loading this related object. Defaults to -1, meaning no limit.
  2030. */
  2031. public $limit=-1;
  2032. /**
  2033. * @var integer offset of the rows to be selected. It is effective only for lazy loading this related object. Defaults to -1, meaning no offset.
  2034. */
  2035. public $offset=-1;
  2036. /**
  2037. * @var string the name of the column that should be used as the key for storing related objects.
  2038. * Defaults to null, meaning using zero-based integer IDs.
  2039. */
  2040. public $index;
  2041. /**
  2042. * @var string the name of the relation that should be used as the bridge to this relation.
  2043. * Defaults to null, meaning don't use any bridge.
  2044. * @since 1.1.7
  2045. */
  2046. public $through;
  2047. /**
  2048. * Merges this relation with a criteria specified dynamically.
  2049. * @param array $criteria the dynamically specified criteria
  2050. * @param boolean $fromScope whether the criteria to be merged is from scopes
  2051. */
  2052. public function mergeWith($criteria,$fromScope=false)
  2053. {
  2054. if($criteria instanceof CDbCriteria)
  2055. $criteria=$criteria->toArray();
  2056. parent::mergeWith($criteria,$fromScope);
  2057. if(isset($criteria['limit']) && $criteria['limit']>0)
  2058. $this->limit=$criteria['limit'];
  2059. if(isset($criteria['offset']) && $criteria['offset']>=0)
  2060. $this->offset=$criteria['offset'];
  2061. if(isset($criteria['index']))
  2062. $this->index=$criteria['index'];
  2063. }
  2064. }
  2065. /**
  2066. * CManyManyRelation represents the parameters specifying a MANY_MANY relation.
  2067. * @author Qiang Xue <qiang.xue@gmail.com>
  2068. * @version $Id$
  2069. * @package system.db.ar
  2070. * @since 1.0
  2071. */
  2072. class CManyManyRelation extends CHasManyRelation
  2073. {
  2074. }
  2075. /**
  2076. * CActiveRecordMetaData represents the meta-data for an Active Record class.
  2077. *
  2078. * @author Qiang Xue <qiang.xue@gmail.com>
  2079. * @version $Id$
  2080. * @package system.db.ar
  2081. * @since 1.0
  2082. */
  2083. class CActiveRecordMetaData
  2084. {
  2085. /**
  2086. * @var CDbTableSchema the table schema information
  2087. */
  2088. public $tableSchema;
  2089. /**
  2090. * @var array table columns
  2091. */
  2092. public $columns;
  2093. /**
  2094. * @var array list of relations
  2095. */
  2096. public $relations=array();
  2097. /**
  2098. * @var array attribute default values
  2099. */
  2100. public $attributeDefaults=array();
  2101. private $_model;
  2102. /**
  2103. * Constructor.
  2104. * @param CActiveRecord $model the model instance
  2105. */
  2106. public function __construct($model)
  2107. {
  2108. $this->_model=$model;
  2109. $tableName=$model->tableName();
  2110. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  2111. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  2112. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  2113. if($table->primaryKey===null)
  2114. {
  2115. $table->primaryKey=$model->primaryKey();
  2116. if(is_string($table->primaryKey) && isset($table->columns[$table->primaryKey]))
  2117. $table->columns[$table->primaryKey]->isPrimaryKey=true;
  2118. else if(is_array($table->primaryKey))
  2119. {
  2120. foreach($table->primaryKey as $name)
  2121. {
  2122. if(isset($table->columns[$name]))
  2123. $table->columns[$name]->isPrimaryKey=true;
  2124. }
  2125. }
  2126. }
  2127. $this->tableSchema=$table;
  2128. $this->columns=$table->columns;
  2129. foreach($table->columns as $name=>$column)
  2130. {
  2131. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  2132. $this->attributeDefaults[$name]=$column->defaultValue;
  2133. }
  2134. foreach($model->relations() as $name=>$config)
  2135. {
  2136. $this->addRelation($name,$config);
  2137. }
  2138. }
  2139. /**
  2140. * Adds a relation.
  2141. *
  2142. * $config is an array with three elements:
  2143. * relation type, the related active record class and the foreign key.
  2144. *
  2145. * @throws CDbException
  2146. * @param string $name $name Name of the relation.
  2147. * @param array $config $config Relation parameters.
  2148. * @return void
  2149. * @since 1.1.2
  2150. */
  2151. public function addRelation($name,$config)
  2152. {
  2153. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  2154. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  2155. else
  2156. throw new CDbException(Yii::t('yii','Active record "{class}" has an invalid configuration for relation "{relation}". It must specify the relation type, the related active record class and the foreign key.', array('{class}'=>get_class($this->_model),'{relation}'=>$name)));
  2157. }
  2158. /**
  2159. * Checks if there is a relation with specified name defined.
  2160. *
  2161. * @param string $name $name Name of the relation.
  2162. * @return boolean
  2163. * @since 1.1.2
  2164. */
  2165. public function hasRelation($name)
  2166. {
  2167. return isset($this->relations[$name]);
  2168. }
  2169. /**
  2170. * Deletes a relation with specified name.
  2171. *
  2172. * @param string $name $name
  2173. * @return void
  2174. * @since 1.1.2
  2175. */
  2176. public function removeRelation($name)
  2177. {
  2178. unset($this->relations[$name]);
  2179. }
  2180. }