PageRenderTime 46ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/db/ar/CActiveRecord.php

https://github.com/joshuaswarren/weatherhub
PHP | 1446 lines | 691 code | 88 blank | 667 comment | 124 complexity | 7155b4e26d6c1daf2dac2d351db7c24f MD5 | raw file
  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. * @author Qiang Xue <qiang.xue@gmail.com>
  18. * @version $Id: CActiveRecord.php 3317 2011-06-24 20:38:49Z qiang.xue $
  19. * @package system.db.ar
  20. * @since 1.0
  21. *
  22. * @property array $attributes
  23. */
  24. abstract class CActiveRecord extends CModel
  25. {
  26. const BELONGS_TO='CBelongsToRelation';
  27. const HAS_ONE='CHasOneRelation';
  28. const HAS_MANY='CHasManyRelation';
  29. const MANY_MANY='CManyManyRelation';
  30. const STAT='CStatRelation';
  31. /**
  32. * @var CDbConnection the default database connection for all active record classes.
  33. * By default, this is the 'db' application component.
  34. * @see getDbConnection
  35. */
  36. public static $db;
  37. private static $_models=array(); // class name => model
  38. private $_md; // meta data
  39. private $_new=false; // whether this instance is new or not
  40. private $_attributes=array(); // attribute name => attribute value
  41. private $_related=array(); // attribute name => related objects
  42. private $_c; // query criteria (used by finder only)
  43. private $_pk; // old primary key value
  44. private $_alias='t'; // the table alias being used for query
  45. /**
  46. * Constructor.
  47. * @param string $scenario scenario name. See {@link CModel::scenario} for more details about this parameter.
  48. */
  49. public function __construct($scenario='insert')
  50. {
  51. if($scenario===null) // internally used by populateRecord() and model()
  52. return;
  53. $this->setScenario($scenario);
  54. $this->setIsNewRecord(true);
  55. $this->_attributes=$this->getMetaData()->attributeDefaults;
  56. $this->init();
  57. $this->attachBehaviors($this->behaviors());
  58. $this->afterConstruct();
  59. }
  60. /**
  61. * Initializes this model.
  62. * This method is invoked when an AR instance is newly created and has
  63. * its {@link scenario} set.
  64. * You may override this method to provide code that is needed to initialize the model (e.g. setting
  65. * initial property values.)
  66. * @since 1.0.8
  67. */
  68. public function init()
  69. {
  70. }
  71. /**
  72. * Sets the parameters about query caching.
  73. * This is a shortcut method to {@link CDbConnection::cache()}.
  74. * It changes the query caching parameter of the {@link dbConnection} instance.
  75. * @param integer $duration the number of seconds that query results may remain valid in cache.
  76. * If this is 0, the caching will be disabled.
  77. * @param CCacheDependency $dependency the dependency that will be used when saving the query results into cache.
  78. * @param integer $queryCount number of SQL queries that need to be cached after calling this method. Defaults to 1,
  79. * meaning that the next SQL query will be cached.
  80. * @return CActiveRecord the active record instance itself.
  81. * @since 1.1.7
  82. */
  83. public function cache($duration, $dependency=null, $queryCount=1)
  84. {
  85. $this->getDbConnection()->cache($duration, $dependency, $queryCount);
  86. return $this;
  87. }
  88. /**
  89. * PHP sleep magic method.
  90. * This method ensures that the model meta data reference is set to null.
  91. * @return array
  92. */
  93. public function __sleep()
  94. {
  95. $this->_md=null;
  96. return array_keys((array)$this);
  97. }
  98. /**
  99. * PHP getter magic method.
  100. * This method is overridden so that AR attributes can be accessed like properties.
  101. * @param string $name property name
  102. * @return mixed property value
  103. * @see getAttribute
  104. */
  105. public function __get($name)
  106. {
  107. if(isset($this->_attributes[$name]))
  108. return $this->_attributes[$name];
  109. else if(isset($this->getMetaData()->columns[$name]))
  110. return null;
  111. else if(isset($this->_related[$name]))
  112. return $this->_related[$name];
  113. else if(isset($this->getMetaData()->relations[$name]))
  114. return $this->getRelated($name);
  115. else
  116. return parent::__get($name);
  117. }
  118. /**
  119. * PHP setter magic method.
  120. * This method is overridden so that AR attributes can be accessed like properties.
  121. * @param string $name property name
  122. * @param mixed $value property value
  123. */
  124. public function __set($name,$value)
  125. {
  126. if($this->setAttribute($name,$value)===false)
  127. {
  128. if(isset($this->getMetaData()->relations[$name]))
  129. $this->_related[$name]=$value;
  130. else
  131. parent::__set($name,$value);
  132. }
  133. }
  134. /**
  135. * Checks if a property value is null.
  136. * This method overrides the parent implementation by checking
  137. * if the named attribute is null or not.
  138. * @param string $name the property name or the event name
  139. * @return boolean whether the property value is null
  140. * @since 1.0.1
  141. */
  142. public function __isset($name)
  143. {
  144. if(isset($this->_attributes[$name]))
  145. return true;
  146. else if(isset($this->getMetaData()->columns[$name]))
  147. return false;
  148. else if(isset($this->_related[$name]))
  149. return true;
  150. else if(isset($this->getMetaData()->relations[$name]))
  151. return $this->getRelated($name)!==null;
  152. else
  153. return parent::__isset($name);
  154. }
  155. /**
  156. * Sets a component property to be null.
  157. * This method overrides the parent implementation by clearing
  158. * the specified attribute value.
  159. * @param string $name the property name or the event name
  160. * @since 1.0.1
  161. */
  162. public function __unset($name)
  163. {
  164. if(isset($this->getMetaData()->columns[$name]))
  165. unset($this->_attributes[$name]);
  166. else if(isset($this->getMetaData()->relations[$name]))
  167. unset($this->_related[$name]);
  168. else
  169. parent::__unset($name);
  170. }
  171. /**
  172. * Calls the named method which is not a class method.
  173. * Do not call this method. This is a PHP magic method that we override
  174. * to implement the named scope feature.
  175. * @param string $name the method name
  176. * @param array $parameters method parameters
  177. * @return mixed the method return value
  178. * @since 1.0.5
  179. */
  180. public function __call($name,$parameters)
  181. {
  182. if(isset($this->getMetaData()->relations[$name]))
  183. {
  184. if(empty($parameters))
  185. return $this->getRelated($name,false);
  186. else
  187. return $this->getRelated($name,false,$parameters[0]);
  188. }
  189. $scopes=$this->scopes();
  190. if(isset($scopes[$name]))
  191. {
  192. $this->getDbCriteria()->mergeWith($scopes[$name]);
  193. return $this;
  194. }
  195. return parent::__call($name,$parameters);
  196. }
  197. /**
  198. * Returns the related record(s).
  199. * This method will return the related record(s) of the current record.
  200. * If the relation is HAS_ONE or BELONGS_TO, it will return a single object
  201. * or null if the object does not exist.
  202. * If the relation is HAS_MANY or MANY_MANY, it will return an array of objects
  203. * or an empty array.
  204. * @param string $name the relation name (see {@link relations})
  205. * @param boolean $refresh whether to reload the related objects from database. Defaults to false.
  206. * @param array $params additional parameters that customize the query conditions as specified in the relation declaration.
  207. * This parameter has been available since version 1.0.5.
  208. * @return mixed the related object(s).
  209. * @throws CDbException if the relation is not specified in {@link relations}.
  210. * @since 1.0.2
  211. */
  212. public function getRelated($name,$refresh=false,$params=array())
  213. {
  214. if(!$refresh && $params===array() && (isset($this->_related[$name]) || array_key_exists($name,$this->_related)))
  215. return $this->_related[$name];
  216. $md=$this->getMetaData();
  217. if(!isset($md->relations[$name]))
  218. throw new CDbException(Yii::t('yii','{class} does not have relation "{name}".',
  219. array('{class}'=>get_class($this), '{name}'=>$name)));
  220. Yii::trace('lazy loading '.get_class($this).'.'.$name,'system.db.ar.CActiveRecord');
  221. $relation=$md->relations[$name];
  222. if($this->getIsNewRecord() && !$refresh && ($relation instanceof CHasOneRelation || $relation instanceof CHasManyRelation))
  223. return $relation instanceof CHasOneRelation ? null : array();
  224. if($params!==array()) // dynamic query
  225. {
  226. $exists=isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  227. if($exists)
  228. $save=$this->_related[$name];
  229. $r=array($name=>$params);
  230. }
  231. else
  232. $r=$name;
  233. unset($this->_related[$name]);
  234. $finder=new CActiveFinder($this,$r);
  235. $finder->lazyFind($this);
  236. if(!isset($this->_related[$name]))
  237. {
  238. if($relation instanceof CHasManyRelation)
  239. $this->_related[$name]=array();
  240. else if($relation instanceof CStatRelation)
  241. $this->_related[$name]=$relation->defaultValue;
  242. else
  243. $this->_related[$name]=null;
  244. }
  245. if($params!==array())
  246. {
  247. $results=$this->_related[$name];
  248. if($exists)
  249. $this->_related[$name]=$save;
  250. else
  251. unset($this->_related[$name]);
  252. return $results;
  253. }
  254. else
  255. return $this->_related[$name];
  256. }
  257. /**
  258. * Returns a value indicating whether the named related object(s) has been loaded.
  259. * @param string $name the relation name
  260. * @return boolean a value indicating whether the named related object(s) has been loaded.
  261. * @since 1.0.3
  262. */
  263. public function hasRelated($name)
  264. {
  265. return isset($this->_related[$name]) || array_key_exists($name,$this->_related);
  266. }
  267. /**
  268. * Returns the query criteria associated with this model.
  269. * @param boolean $createIfNull whether to create a criteria instance if it does not exist. Defaults to true.
  270. * @return CDbCriteria the query criteria that is associated with this model.
  271. * This criteria is mainly used by {@link scopes named scope} feature to accumulate
  272. * different criteria specifications.
  273. * @since 1.0.5
  274. */
  275. public function getDbCriteria($createIfNull=true)
  276. {
  277. if($this->_c===null)
  278. {
  279. if(($c=$this->defaultScope())!==array() || $createIfNull)
  280. $this->_c=new CDbCriteria($c);
  281. }
  282. return $this->_c;
  283. }
  284. /**
  285. * Sets the query criteria for the current model.
  286. * @param CDbCriteria $criteria the query criteria
  287. * @since 1.1.3
  288. */
  289. public function setDbCriteria($criteria)
  290. {
  291. $this->_c=$criteria;
  292. }
  293. /**
  294. * Returns the default named scope that should be implicitly applied to all queries for this model.
  295. * Note, default scope only applies to SELECT queries. It is ignored for INSERT, UPDATE and DELETE queries.
  296. * The default implementation simply returns an empty array. You may override this method
  297. * if the model needs to be queried with some default criteria (e.g. only active records should be returned).
  298. * @return array the query criteria. This will be used as the parameter to the constructor
  299. * of {@link CDbCriteria}.
  300. * @since 1.0.5
  301. */
  302. public function defaultScope()
  303. {
  304. return array();
  305. }
  306. /**
  307. * Resets all scopes and criterias applied including default scope.
  308. *
  309. * @return CActiveRecord
  310. * @since 1.1.2
  311. */
  312. public function resetScope()
  313. {
  314. $this->_c=new CDbCriteria();
  315. return $this;
  316. }
  317. /**
  318. * Returns the static model of the specified AR class.
  319. * The model returned is a static instance of the AR class.
  320. * It is provided for invoking class-level methods (something similar to static class methods.)
  321. *
  322. * EVERY derived AR class must override this method as follows,
  323. * <pre>
  324. * public static function model($className=__CLASS__)
  325. * {
  326. * return parent::model($className);
  327. * }
  328. * </pre>
  329. *
  330. * @param string $className active record class name.
  331. * @return CActiveRecord active record model instance.
  332. */
  333. public static function model($className=__CLASS__)
  334. {
  335. if(isset(self::$_models[$className]))
  336. return self::$_models[$className];
  337. else
  338. {
  339. $model=self::$_models[$className]=new $className(null);
  340. $model->_md=new CActiveRecordMetaData($model);
  341. $model->attachBehaviors($model->behaviors());
  342. return $model;
  343. }
  344. }
  345. /**
  346. * Returns the meta-data for this AR
  347. * @return CActiveRecordMetaData the meta for this AR class.
  348. */
  349. public function getMetaData()
  350. {
  351. if($this->_md!==null)
  352. return $this->_md;
  353. else
  354. return $this->_md=self::model(get_class($this))->_md;
  355. }
  356. /**
  357. * Refreshes the meta data for this AR class.
  358. * By calling this method, this AR class will regenerate the meta data needed.
  359. * This is useful if the table schema has been changed and you want to use the latest
  360. * available table schema. Make sure you have called {@link CDbSchema::refresh}
  361. * before you call this method. Otherwise, old table schema data will still be used.
  362. * @since 1.0.8
  363. */
  364. public function refreshMetaData()
  365. {
  366. $finder=self::model(get_class($this));
  367. $finder->_md=new CActiveRecordMetaData($finder);
  368. if($this!==$finder)
  369. $this->_md=$finder->_md;
  370. }
  371. /**
  372. * Returns the name of the associated database table.
  373. * By default this method returns the class name as the table name.
  374. * You may override this method if the table is not named after this convention.
  375. * @return string the table name
  376. */
  377. public function tableName()
  378. {
  379. return get_class($this);
  380. }
  381. /**
  382. * Returns the primary key of the associated database table.
  383. * This method is meant to be overridden in case when the table is not defined with a primary key
  384. * (for some legency database). If the table is already defined with a primary key,
  385. * you do not need to override this method. The default implementation simply returns null,
  386. * meaning using the primary key defined in the database.
  387. * @return mixed the primary key of the associated database table.
  388. * If the key is a single column, it should return the column name;
  389. * If the key is a composite one consisting of several columns, it should
  390. * return the array of the key column names.
  391. * @since 1.0.4
  392. */
  393. public function primaryKey()
  394. {
  395. }
  396. /**
  397. * This method should be overridden to declare related objects.
  398. *
  399. * There are four types of relations that may exist between two active record objects:
  400. * <ul>
  401. * <li>BELONGS_TO: e.g. a member belongs to a team;</li>
  402. * <li>HAS_ONE: e.g. a member has at most one profile;</li>
  403. * <li>HAS_MANY: e.g. a team has many members;</li>
  404. * <li>MANY_MANY: e.g. a member has many skills and a skill belongs to a member.</li>
  405. * </ul>
  406. *
  407. * Besides the above relation types, a special relation called STAT is also supported
  408. * that can be used to perform statistical query (or aggregational query).
  409. * It retrieves the aggregational information about the related objects, such as the number
  410. * of comments for each post, the average rating for each product, etc.
  411. *
  412. * Each kind of related objects is defined in this method as an array with the following elements:
  413. * <pre>
  414. * 'varName'=>array('relationType', 'className', 'foreign_key', ...additional options)
  415. * </pre>
  416. * where 'varName' refers to the name of the variable/property that the related object(s) can
  417. * be accessed through; 'relationType' refers to the type of the relation, which can be one of the
  418. * following four constants: self::BELONGS_TO, self::HAS_ONE, self::HAS_MANY and self::MANY_MANY;
  419. * 'className' refers to the name of the active record class that the related object(s) is of;
  420. * and 'foreign_key' states the foreign key that relates the two kinds of active record.
  421. * Note, for composite foreign keys, they must be listed together, separated by commas;
  422. * and for foreign keys used in MANY_MANY relation, the joining table must be declared as well
  423. * (e.g. 'join_table(fk1, fk2)').
  424. *
  425. * Additional options may be specified as name-value pairs in the rest array elements:
  426. * <ul>
  427. * <li>'select': string|array, a list of columns to be selected. Defaults to '*', meaning all columns.
  428. * Column names should be disambiguated if they appear in an expression (e.g. COUNT(relationName.name) AS name_count).</li>
  429. * <li>'condition': string, the WHERE clause. Defaults to empty. Note, column references need to
  430. * be disambiguated with prefix 'relationName.' (e.g. relationName.age&gt;20)</li>
  431. * <li>'order': string, the ORDER BY clause. Defaults to empty. Note, column references need to
  432. * be disambiguated with prefix 'relationName.' (e.g. relationName.age DESC)</li>
  433. * <li>'with': string|array, a list of child related objects that should be loaded together with this object.
  434. * Note, this is only honored by lazy loading, not eager loading.</li>
  435. * <li>'joinType': type of join. Defaults to 'LEFT OUTER JOIN'.</li>
  436. * <li>'alias': the alias for the table associated with this relationship.
  437. * This option has been available since version 1.0.1. It defaults to null,
  438. * meaning the table alias is the same as the relation name.</li>
  439. * <li>'params': the parameters to be bound to the generated SQL statement.
  440. * This should be given as an array of name-value pairs. This option has been
  441. * available since version 1.0.3.</li>
  442. * <li>'on': the ON clause. The condition specified here will be appended
  443. * to the joining condition using the AND operator. This option has been
  444. * available since version 1.0.2.</li>
  445. * <li>'index': the name of the column whose values should be used as keys
  446. * of the array that stores related objects. This option is only available to
  447. * HAS_MANY and MANY_MANY relations. This option has been available since version 1.0.7.</li>
  448. * </ul>
  449. *
  450. * The following options are available for certain relations when lazy loading:
  451. * <ul>
  452. * <li>'group': string, the GROUP BY clause. Defaults to empty. Note, column references need to
  453. * be disambiguated with prefix 'relationName.' (e.g. relationName.age). This option only applies to HAS_MANY and MANY_MANY relations.</li>
  454. * <li>'having': string, the HAVING clause. Defaults to empty. Note, column references need to
  455. * be disambiguated with prefix 'relationName.' (e.g. relationName.age). This option only applies to HAS_MANY and MANY_MANY relations.</li>
  456. * <li>'limit': limit of the rows to be selected. This option does not apply to BELONGS_TO relation.</li>
  457. * <li>'offset': offset of the rows to be selected. This option does not apply to BELONGS_TO relation.</li>
  458. * <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>
  459. * </ul>
  460. *
  461. * Below is an example declaring related objects for 'Post' active record class:
  462. * <pre>
  463. * return array(
  464. * 'author'=>array(self::BELONGS_TO, 'User', 'author_id'),
  465. * 'comments'=>array(self::HAS_MANY, 'Comment', 'post_id', 'with'=>'author', 'order'=>'create_time DESC'),
  466. * 'tags'=>array(self::MANY_MANY, 'Tag', 'post_tag(post_id, tag_id)', 'order'=>'name'),
  467. * );
  468. * </pre>
  469. *
  470. * @return array list of related object declarations. Defaults to empty array.
  471. */
  472. public function relations()
  473. {
  474. return array();
  475. }
  476. /**
  477. * Returns the declaration of named scopes.
  478. * A named scope represents a query criteria that can be chained together with
  479. * other named scopes and applied to a query. This method should be overridden
  480. * by child classes to declare named scopes for the particular AR classes.
  481. * For example, the following code declares two named scopes: 'recently' and
  482. * 'published'.
  483. * <pre>
  484. * return array(
  485. * 'published'=>array(
  486. * 'condition'=>'status=1',
  487. * ),
  488. * 'recently'=>array(
  489. * 'order'=>'create_time DESC',
  490. * 'limit'=>5,
  491. * ),
  492. * );
  493. * </pre>
  494. * If the above scopes are declared in a 'Post' model, we can perform the following
  495. * queries:
  496. * <pre>
  497. * $posts=Post::model()->published()->findAll();
  498. * $posts=Post::model()->published()->recently()->findAll();
  499. * $posts=Post::model()->published()->with('comments')->findAll();
  500. * </pre>
  501. * Note that the last query is a relational query.
  502. *
  503. * @return array the scope definition. The array keys are scope names; the array
  504. * values are the corresponding scope definitions. Each scope definition is represented
  505. * as an array whose keys must be properties of {@link CDbCriteria}.
  506. * @since 1.0.5
  507. */
  508. public function scopes()
  509. {
  510. return array();
  511. }
  512. /**
  513. * Returns the list of all attribute names of the model.
  514. * This would return all column names of the table associated with this AR class.
  515. * @return array list of attribute names.
  516. * @since 1.0.1
  517. */
  518. public function attributeNames()
  519. {
  520. return array_keys($this->getMetaData()->columns);
  521. }
  522. /**
  523. * Returns the text label for the specified attribute.
  524. * This method overrides the parent implementation by supporting
  525. * returning the label defined in relational object.
  526. * In particular, if the attribute name is in the form of "post.author.name",
  527. * then this method will derive the label from the "author" relation's "name" attribute.
  528. * @param string $attribute the attribute name
  529. * @return string the attribute label
  530. * @see generateAttributeLabel
  531. * @since 1.1.4
  532. */
  533. public function getAttributeLabel($attribute)
  534. {
  535. $labels=$this->attributeLabels();
  536. if(isset($labels[$attribute]))
  537. return $labels[$attribute];
  538. else if(strpos($attribute,'.')!==false)
  539. {
  540. $segs=explode('.',$attribute);
  541. $name=array_pop($segs);
  542. $model=$this;
  543. foreach($segs as $seg)
  544. {
  545. $relations=$model->getMetaData()->relations;
  546. if(isset($relations[$seg]))
  547. $model=CActiveRecord::model($relations[$seg]->className);
  548. else
  549. break;
  550. }
  551. return $model->getAttributeLabel($name);
  552. }
  553. else
  554. return $this->generateAttributeLabel($attribute);
  555. }
  556. /**
  557. * Returns the database connection used by active record.
  558. * By default, the "db" application component is used as the database connection.
  559. * You may override this method if you want to use a different database connection.
  560. * @return CDbConnection the database connection used by active record.
  561. */
  562. public function getDbConnection()
  563. {
  564. if(self::$db!==null)
  565. return self::$db;
  566. else
  567. {
  568. self::$db=Yii::app()->getDb();
  569. if(self::$db instanceof CDbConnection)
  570. return self::$db;
  571. else
  572. throw new CDbException(Yii::t('yii','Active Record requires a "db" CDbConnection application component.'));
  573. }
  574. }
  575. /**
  576. * Returns the named relation declared for this AR class.
  577. * @param string $name the relation name
  578. * @return CActiveRelation the named relation declared for this AR class. Null if the relation does not exist.
  579. */
  580. public function getActiveRelation($name)
  581. {
  582. return isset($this->getMetaData()->relations[$name]) ? $this->getMetaData()->relations[$name] : null;
  583. }
  584. /**
  585. * Returns the metadata of the table that this AR belongs to
  586. * @return CDbTableSchema the metadata of the table that this AR belongs to
  587. */
  588. public function getTableSchema()
  589. {
  590. return $this->getMetaData()->tableSchema;
  591. }
  592. /**
  593. * Returns the command builder used by this AR.
  594. * @return CDbCommandBuilder the command builder used by this AR
  595. */
  596. public function getCommandBuilder()
  597. {
  598. return $this->getDbConnection()->getSchema()->getCommandBuilder();
  599. }
  600. /**
  601. * Checks whether this AR has the named attribute
  602. * @param string $name attribute name
  603. * @return boolean whether this AR has the named attribute (table column).
  604. */
  605. public function hasAttribute($name)
  606. {
  607. return isset($this->getMetaData()->columns[$name]);
  608. }
  609. /**
  610. * Returns the named attribute value.
  611. * If this is a new record and the attribute is not set before,
  612. * the default column value will be returned.
  613. * If this record is the result of a query and the attribute is not loaded,
  614. * null will be returned.
  615. * You may also use $this->AttributeName to obtain the attribute value.
  616. * @param string $name the attribute name
  617. * @return mixed the attribute value. Null if the attribute is not set or does not exist.
  618. * @see hasAttribute
  619. */
  620. public function getAttribute($name)
  621. {
  622. if(property_exists($this,$name))
  623. return $this->$name;
  624. else if(isset($this->_attributes[$name]))
  625. return $this->_attributes[$name];
  626. }
  627. /**
  628. * Sets the named attribute value.
  629. * You may also use $this->AttributeName to set the attribute value.
  630. * @param string $name the attribute name
  631. * @param mixed $value the attribute value.
  632. * @return boolean whether the attribute exists and the assignment is conducted successfully
  633. * @see hasAttribute
  634. */
  635. public function setAttribute($name,$value)
  636. {
  637. if(property_exists($this,$name))
  638. $this->$name=$value;
  639. else if(isset($this->getMetaData()->columns[$name]))
  640. $this->_attributes[$name]=$value;
  641. else
  642. return false;
  643. return true;
  644. }
  645. /**
  646. * Do not call this method. This method is used internally by {@link CActiveFinder} to populate
  647. * related objects. This method adds a related object to this record.
  648. * @param string $name attribute name
  649. * @param mixed $record the related record
  650. * @param mixed $index the index value in the related object collection.
  651. * If true, it means using zero-based integer index.
  652. * If false, it means a HAS_ONE or BELONGS_TO object and no index is needed.
  653. */
  654. public function addRelatedRecord($name,$record,$index)
  655. {
  656. if($index!==false)
  657. {
  658. if(!isset($this->_related[$name]))
  659. $this->_related[$name]=array();
  660. if($record instanceof CActiveRecord)
  661. {
  662. if($index===true)
  663. $this->_related[$name][]=$record;
  664. else
  665. $this->_related[$name][$index]=$record;
  666. }
  667. }
  668. else if(!isset($this->_related[$name]))
  669. $this->_related[$name]=$record;
  670. }
  671. /**
  672. * Returns all column attribute values.
  673. * Note, related objects are not returned.
  674. * @param mixed $names names of attributes whose value needs to be returned.
  675. * If this is true (default), then all attribute values will be returned, including
  676. * those that are not loaded from DB (null will be returned for those attributes).
  677. * If this is null, all attributes except those that are not loaded from DB will be returned.
  678. * @return array attribute values indexed by attribute names.
  679. */
  680. public function getAttributes($names=true)
  681. {
  682. $attributes=$this->_attributes;
  683. foreach($this->getMetaData()->columns as $name=>$column)
  684. {
  685. if(property_exists($this,$name))
  686. $attributes[$name]=$this->$name;
  687. else if($names===true && !isset($attributes[$name]))
  688. $attributes[$name]=null;
  689. }
  690. if(is_array($names))
  691. {
  692. $attrs=array();
  693. foreach($names as $name)
  694. {
  695. if(property_exists($this,$name))
  696. $attrs[$name]=$this->$name;
  697. else
  698. $attrs[$name]=isset($attributes[$name])?$attributes[$name]:null;
  699. }
  700. return $attrs;
  701. }
  702. else
  703. return $attributes;
  704. }
  705. /**
  706. * Saves the current record.
  707. *
  708. * The record is inserted as a row into the database table if its {@link isNewRecord}
  709. * property is true (usually the case when the record is created using the 'new'
  710. * operator). Otherwise, it will be used to update the corresponding row in the table
  711. * (usually the case if the record is obtained using one of those 'find' methods.)
  712. *
  713. * Validation will be performed before saving the record. If the validation fails,
  714. * the record will not be saved. You can call {@link getErrors()} to retrieve the
  715. * validation errors.
  716. *
  717. * If the record is saved via insertion, its {@link isNewRecord} property will be
  718. * set false, and its {@link scenario} property will be set to be 'update'.
  719. * And if its primary key is auto-incremental and is not set before insertion,
  720. * the primary key will be populated with the automatically generated key value.
  721. *
  722. * @param boolean $runValidation whether to perform validation before saving the record.
  723. * If the validation fails, the record will not be saved to database.
  724. * @param array $attributes list of attributes that need to be saved. Defaults to null,
  725. * meaning all attributes that are loaded from DB will be saved.
  726. * @return boolean whether the saving succeeds
  727. */
  728. public function save($runValidation=true,$attributes=null)
  729. {
  730. if(!$runValidation || $this->validate($attributes))
  731. return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);
  732. else
  733. return false;
  734. }
  735. /**
  736. * Returns if the current record is new.
  737. * @return boolean whether the record is new and should be inserted when calling {@link save}.
  738. * This property is automatically set in constructor and {@link populateRecord}.
  739. * Defaults to false, but it will be set to true if the instance is created using
  740. * the new operator.
  741. */
  742. public function getIsNewRecord()
  743. {
  744. return $this->_new;
  745. }
  746. /**
  747. * Sets if the record is new.
  748. * @param boolean $value whether the record is new and should be inserted when calling {@link save}.
  749. * @see getIsNewRecord
  750. */
  751. public function setIsNewRecord($value)
  752. {
  753. $this->_new=$value;
  754. }
  755. /**
  756. * This event is raised before the record is saved.
  757. * By setting {@link CModelEvent::isValid} to be false, the normal {@link save()} process will be stopped.
  758. * @param CModelEvent $event the event parameter
  759. * @since 1.0.2
  760. */
  761. public function onBeforeSave($event)
  762. {
  763. $this->raiseEvent('onBeforeSave',$event);
  764. }
  765. /**
  766. * This event is raised after the record is saved.
  767. * @param CEvent $event the event parameter
  768. * @since 1.0.2
  769. */
  770. public function onAfterSave($event)
  771. {
  772. $this->raiseEvent('onAfterSave',$event);
  773. }
  774. /**
  775. * This event is raised before the record is deleted.
  776. * By setting {@link CModelEvent::isValid} to be false, the normal {@link delete()} process will be stopped.
  777. * @param CModelEvent $event the event parameter
  778. * @since 1.0.2
  779. */
  780. public function onBeforeDelete($event)
  781. {
  782. $this->raiseEvent('onBeforeDelete',$event);
  783. }
  784. /**
  785. * This event is raised after the record is deleted.
  786. * @param CEvent $event the event parameter
  787. * @since 1.0.2
  788. */
  789. public function onAfterDelete($event)
  790. {
  791. $this->raiseEvent('onAfterDelete',$event);
  792. }
  793. /**
  794. * This event is raised before an AR finder performs a find call.
  795. * In this event, the {@link CModelEvent::criteria} property contains the query criteria
  796. * passed as parameters to those find methods. If you want to access
  797. * the query criteria specified in scopes, please use {@link getDbCriteria()}.
  798. * You can modify either criteria to customize them based on needs.
  799. * @param CModelEvent $event the event parameter
  800. * @see beforeFind
  801. * @since 1.0.9
  802. */
  803. public function onBeforeFind($event)
  804. {
  805. $this->raiseEvent('onBeforeFind',$event);
  806. }
  807. /**
  808. * This event is raised after the record is instantiated by a find method.
  809. * @param CEvent $event the event parameter
  810. * @since 1.0.2
  811. */
  812. public function onAfterFind($event)
  813. {
  814. $this->raiseEvent('onAfterFind',$event);
  815. }
  816. /**
  817. * This method is invoked before saving a record (after validation, if any).
  818. * The default implementation raises the {@link onBeforeSave} event.
  819. * You may override this method to do any preparation work for record saving.
  820. * Use {@link isNewRecord} to determine whether the saving is
  821. * for inserting or updating record.
  822. * Make sure you call the parent implementation so that the event is raised properly.
  823. * @return boolean whether the saving should be executed. Defaults to true.
  824. */
  825. protected function beforeSave()
  826. {
  827. if($this->hasEventHandler('onBeforeSave'))
  828. {
  829. $event=new CModelEvent($this);
  830. $this->onBeforeSave($event);
  831. return $event->isValid;
  832. }
  833. else
  834. return true;
  835. }
  836. /**
  837. * This method is invoked after saving a record successfully.
  838. * The default implementation raises the {@link onAfterSave} event.
  839. * You may override this method to do postprocessing after record saving.
  840. * Make sure you call the parent implementation so that the event is raised properly.
  841. */
  842. protected function afterSave()
  843. {
  844. if($this->hasEventHandler('onAfterSave'))
  845. $this->onAfterSave(new CEvent($this));
  846. }
  847. /**
  848. * This method is invoked before deleting a record.
  849. * The default implementation raises the {@link onBeforeDelete} event.
  850. * You may override this method to do any preparation work for record deletion.
  851. * Make sure you call the parent implementation so that the event is raised properly.
  852. * @return boolean whether the record should be deleted. Defaults to true.
  853. */
  854. protected function beforeDelete()
  855. {
  856. if($this->hasEventHandler('onBeforeDelete'))
  857. {
  858. $event=new CModelEvent($this);
  859. $this->onBeforeDelete($event);
  860. return $event->isValid;
  861. }
  862. else
  863. return true;
  864. }
  865. /**
  866. * This method is invoked after deleting a record.
  867. * The default implementation raises the {@link onAfterDelete} event.
  868. * You may override this method to do postprocessing after the record is deleted.
  869. * Make sure you call the parent implementation so that the event is raised properly.
  870. */
  871. protected function afterDelete()
  872. {
  873. if($this->hasEventHandler('onAfterDelete'))
  874. $this->onAfterDelete(new CEvent($this));
  875. }
  876. /**
  877. * This method is invoked before an AR finder executes a find call.
  878. * The find calls include {@link find}, {@link findAll}, {@link findByPk},
  879. * {@link findAllByPk}, {@link findByAttributes} and {@link findAllByAttributes}.
  880. * The default implementation raises the {@link onBeforeFind} event.
  881. * If you override this method, make sure you call the parent implementation
  882. * so that the event is raised properly.
  883. *
  884. * Starting from version 1.1.5, this method may be called with a hidden {@link CDbCriteria}
  885. * parameter which represents the current query criteria as passed to a find method of AR.
  886. *
  887. * @since 1.0.9
  888. */
  889. protected function beforeFind()
  890. {
  891. if($this->hasEventHandler('onBeforeFind'))
  892. {
  893. $event=new CModelEvent($this);
  894. // for backward compatibility
  895. $event->criteria=func_num_args()>0 ? func_get_arg(0) : null;
  896. $this->onBeforeFind($event);
  897. }
  898. }
  899. /**
  900. * This method is invoked after each record is instantiated by a find method.
  901. * The default implementation raises the {@link onAfterFind} event.
  902. * You may override this method to do postprocessing after each newly found record is instantiated.
  903. * Make sure you call the parent implementation so that the event is raised properly.
  904. */
  905. protected function afterFind()
  906. {
  907. if($this->hasEventHandler('onAfterFind'))
  908. $this->onAfterFind(new CEvent($this));
  909. }
  910. /**
  911. * Calls {@link beforeFind}.
  912. * This method is internally used.
  913. * @since 1.0.11
  914. */
  915. public function beforeFindInternal()
  916. {
  917. $this->beforeFind();
  918. }
  919. /**
  920. * Calls {@link afterFind}.
  921. * This method is internally used.
  922. * @since 1.0.3
  923. */
  924. public function afterFindInternal()
  925. {
  926. $this->afterFind();
  927. }
  928. /**
  929. * Inserts a row into the table based on this active record attributes.
  930. * If the table's primary key is auto-incremental and is null before insertion,
  931. * it will be populated with the actual value after insertion.
  932. * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
  933. * After the record is inserted to DB successfully, its {@link isNewRecord} property will be set false,
  934. * and its {@link scenario} property will be set to be 'update'.
  935. * @param array $attributes list of attributes that need to be saved. Defaults to null,
  936. * meaning all attributes that are loaded from DB will be saved.
  937. * @return boolean whether the attributes are valid and the record is inserted successfully.
  938. * @throws CException if the record is not new
  939. */
  940. public function insert($attributes=null)
  941. {
  942. if(!$this->getIsNewRecord())
  943. throw new CDbException(Yii::t('yii','The active record cannot be inserted to database because it is not new.'));
  944. if($this->beforeSave())
  945. {
  946. Yii::trace(get_class($this).'.insert()','system.db.ar.CActiveRecord');
  947. $builder=$this->getCommandBuilder();
  948. $table=$this->getMetaData()->tableSchema;
  949. $command=$builder->createInsertCommand($table,$this->getAttributes($attributes));
  950. if($command->execute())
  951. {
  952. $primaryKey=$table->primaryKey;
  953. if($table->sequenceName!==null)
  954. {
  955. if(is_string($primaryKey) && $this->$primaryKey===null)
  956. $this->$primaryKey=$builder->getLastInsertID($table);
  957. else if(is_array($primaryKey))
  958. {
  959. foreach($primaryKey as $pk)
  960. {
  961. if($this->$pk===null)
  962. {
  963. $this->$pk=$builder->getLastInsertID($table);
  964. break;
  965. }
  966. }
  967. }
  968. }
  969. $this->_pk=$this->getPrimaryKey();
  970. $this->afterSave();
  971. $this->setIsNewRecord(false);
  972. $this->setScenario('update');
  973. return true;
  974. }
  975. }
  976. return false;
  977. }
  978. /**
  979. * Updates the row represented by this active record.
  980. * All loaded attributes will be saved to the database.
  981. * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
  982. * @param array $attributes list of attributes that need to be saved. Defaults to null,
  983. * meaning all attributes that are loaded from DB will be saved.
  984. * @return boolean whether the update is successful
  985. * @throws CException if the record is new
  986. */
  987. public function update($attributes=null)
  988. {
  989. if($this->getIsNewRecord())
  990. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  991. if($this->beforeSave())
  992. {
  993. Yii::trace(get_class($this).'.update()','system.db.ar.CActiveRecord');
  994. if($this->_pk===null)
  995. $this->_pk=$this->getPrimaryKey();
  996. $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
  997. $this->_pk=$this->getPrimaryKey();
  998. $this->afterSave();
  999. return true;
  1000. }
  1001. else
  1002. return false;
  1003. }
  1004. /**
  1005. * Saves a selected list of attributes.
  1006. * Unlike {@link save}, this method only saves the specified attributes
  1007. * of an existing row dataset and does NOT call either {@link beforeSave} or {@link afterSave}.
  1008. * Also note that this method does neither attribute filtering nor validation.
  1009. * So do not use this method with untrusted data (such as user posted data).
  1010. * You may consider the following alternative if you want to do so:
  1011. * <pre>
  1012. * $postRecord=Post::model()->findByPk($postID);
  1013. * $postRecord->attributes=$_POST['post'];
  1014. * $postRecord->save();
  1015. * </pre>
  1016. * @param array $attributes attributes to be updated. Each element represents an attribute name
  1017. * or an attribute value indexed by its name. If the latter, the record's
  1018. * attribute will be changed accordingly before saving.
  1019. * @return boolean whether the update is successful
  1020. * @throws CException if the record is new or any database error
  1021. */
  1022. public function saveAttributes($attributes)
  1023. {
  1024. if(!$this->getIsNewRecord())
  1025. {
  1026. Yii::trace(get_class($this).'.saveAttributes()','system.db.ar.CActiveRecord');
  1027. $values=array();
  1028. foreach($attributes as $name=>$value)
  1029. {
  1030. if(is_integer($name))
  1031. $values[$value]=$this->$value;
  1032. else
  1033. $values[$name]=$this->$name=$value;
  1034. }
  1035. if($this->_pk===null)
  1036. $this->_pk=$this->getPrimaryKey();
  1037. if($this->updateByPk($this->getOldPrimaryKey(),$values)>0)
  1038. {
  1039. $this->_pk=$this->getPrimaryKey();
  1040. return true;
  1041. }
  1042. else
  1043. return false;
  1044. }
  1045. else
  1046. throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
  1047. }
  1048. /**
  1049. * Saves one or several counter columns for the current AR object.
  1050. * Note that this method differs from {@link updateCounters} in that it only
  1051. * saves the current AR object.
  1052. * An example usage is as follows:
  1053. * <pre>
  1054. * $postRecord=Post::model()->findByPk($postID);
  1055. * $postRecord->saveCounters(array('view_count'=>1));
  1056. * </pre>
  1057. * Use negative values if you want to decrease the counters.
  1058. * @param array $counters the counters to be updated (column name=>increment value)
  1059. * @return boolean whether the saving is successful
  1060. * @see updateCounters
  1061. * @since 1.1.8
  1062. */
  1063. public function saveCounters($counters)
  1064. {
  1065. Yii::trace(get_class($this).'.saveCounters()','system.db.ar.CActiveRecord');
  1066. $builder=$this->getCommandBuilder();
  1067. $table=$this->getTableSchema();
  1068. $criteria=$builder->createPkCriteria($table,$this->getOldPrimaryKey());
  1069. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  1070. if($command->execute())
  1071. {
  1072. foreach($counters as $name=>$value)
  1073. $this->$name=$this->$name+$value;
  1074. return true;
  1075. }
  1076. else
  1077. return false;
  1078. }
  1079. /**
  1080. * Deletes the row corresponding to this active record.
  1081. * @return boolean whether the deletion is successful.
  1082. * @throws CException if the record is new
  1083. */
  1084. public function delete()
  1085. {
  1086. if(!$this->getIsNewRecord())
  1087. {
  1088. Yii::trace(get_class($this).'.delete()','system.db.ar.CActiveRecord');
  1089. if($this->beforeDelete())
  1090. {
  1091. $result=$this->deleteByPk($this->getPrimaryKey())>0;
  1092. $this->afterDelete();
  1093. return $result;
  1094. }
  1095. else
  1096. return false;
  1097. }
  1098. else
  1099. throw new CDbException(Yii::t('yii','The active record cannot be deleted because it is new.'));
  1100. }
  1101. /**
  1102. * Repopulates this active record with the latest data.
  1103. * @return boolean whether the row still exists in the database. If true, the latest data will be populated to this active record.
  1104. */
  1105. public function refresh()
  1106. {
  1107. Yii::trace(get_class($this).'.refresh()','system.db.ar.CActiveRecord');
  1108. if(!$this->getIsNewRecord() && ($record=$this->findByPk($this->getPrimaryKey()))!==null)
  1109. {
  1110. $this->_attributes=array();
  1111. $this->_related=array();
  1112. foreach($this->getMetaData()->columns as $name=>$column)
  1113. {
  1114. if(property_exists($this,$name))
  1115. $this->$name=$record->$name;
  1116. else
  1117. $this->_attributes[$name]=$record->$name;
  1118. }
  1119. return true;
  1120. }
  1121. else
  1122. return false;
  1123. }
  1124. /**
  1125. * Compares current active record with another one.
  1126. * The comparison is made by comparing table name and the primary key values of the two active records.
  1127. * @param CActiveRecord $record record to compare to
  1128. * @return boolean whether the two active records refer to the same row in the database table.
  1129. */
  1130. public function equals($record)
  1131. {
  1132. return $this->tableName()===$record->tableName() && $this->getPrimaryKey()===$record->getPrimaryKey();
  1133. }
  1134. /**
  1135. * Returns the primary key value.
  1136. * @return mixed the primary key value. An array (column name=>column value) is returned if the primary key is composite.
  1137. * If primary key is not defined, null will be returned.
  1138. */
  1139. public function getPrimaryKey()
  1140. {
  1141. $table=$this->getMetaData()->tableSchema;
  1142. if(is_string($table->primaryKey))
  1143. return $this->{$table->primaryKey};
  1144. else if(is_array($table->primaryKey))
  1145. {
  1146. $values=array();
  1147. foreach($table->primaryKey as $name)
  1148. $values[$name]=$this->$name;
  1149. return $values;
  1150. }
  1151. else
  1152. return null;
  1153. }
  1154. /**
  1155. * Sets the primary key value.
  1156. * After calling this method, the old primary key value can be obtained from {@link oldPrimaryKey}.
  1157. * @param mixed $value the new primary key value. If the primary key is composite, the new value
  1158. * should be provided as an array (column name=>column value).
  1159. * @since 1.1.0
  1160. */
  1161. public function setPrimaryKey($value)
  1162. {
  1163. $this->_pk=$this->getPrimaryKey();
  1164. $table=$this->getMetaData()->tableSchema;
  1165. if(is_string($table->primaryKey))
  1166. $this->{$table->primaryKey}=$value;
  1167. else if(is_array($table->primaryKey))
  1168. {
  1169. foreach($table->primaryKey as $name)
  1170. $this->$name=$value[$name];
  1171. }
  1172. }
  1173. /**
  1174. * Returns the old primary key value.
  1175. * This refers to the primary key value that is populated into the record
  1176. * after executing a find method (e.g. find(), findAll()).
  1177. * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
  1178. * @return mixed the old primary key value. An array (column name=>column value) is returned if the primary key is composite.
  1179. * If primary key is not defined, null will be returned.
  1180. * @since 1.1.0
  1181. */
  1182. public function getOldPrimaryKey()
  1183. {
  1184. return $this->_pk;
  1185. }
  1186. /**
  1187. * Sets the old primary key value.
  1188. * @param mixed $value the old primary key value.
  1189. * @since 1.1.3
  1190. */
  1191. public function setOldPrimaryKey($value)
  1192. {
  1193. $this->_pk=$value;
  1194. }
  1195. /**
  1196. * Performs the actual DB query and populates the AR objects with the query result.
  1197. * This method is mainly internally used by other AR query methods.
  1198. * @param CDbCriteria $criteria the query criteria
  1199. * @param boolean $all whether to return all data
  1200. * @return mixed the AR objects populated with the query result
  1201. * @since 1.1.7
  1202. */
  1203. protected function query($criteria,$all=false)
  1204. {
  1205. $this->beforeFind();
  1206. $this->applyScopes($criteria);
  1207. if(empty($criteria->with))
  1208. {
  1209. if(!$all)
  1210. $criteria->limit=1;
  1211. $command=$this->getCommandBuilder()->createFindCommand($this->getTableSchema(),$criteria);
  1212. return $all ? $this->populateRecords($command->queryAll(), true, $criteria->index) : $this->populateRecord($command->queryRow());
  1213. }
  1214. else
  1215. {
  1216. $finder=new CActiveFinder($this,$criteria->with);
  1217. return $finder->query($criteria,$all);
  1218. }
  1219. }
  1220. /**
  1221. * Applies the query scopes to the given criteria.
  1222. * This method merges {@link dbCriteria} with the given criteria parameter.
  1223. * It then resets {@link dbCriteria} to be null.
  1224. * @param CDbCriteria $criteria the query criteria. This parameter may be modified by merging {@link dbCriteria}.
  1225. * @since 1.0.12
  1226. */
  1227. public function applyScopes(&$criteria)
  1228. {
  1229. if(!empty($criteria->scopes))
  1230. {
  1231. $scs=$this->scopes();
  1232. $c=$this->getDbCriteria();
  1233. foreach((array)$criteria->scopes as $k=>$v)
  1234. {
  1235. if(is_integer($k))
  1236. {
  1237. if(is_string($v))
  1238. {
  1239. if(isset($scs[$v]))
  1240. {
  1241. $c->mergeWith($scs[$v],true);
  1242. continue;
  1243. }
  1244. $scope=$v;
  1245. $params=array();
  1246. }
  1247. else if(is_array($v))
  1248. {
  1249. $scope=key($v);
  1250. $params=current($v);
  1251. }
  1252. }
  1253. else if(is_string($k))
  1254. {
  1255. $scope=$k;
  1256. $params=$v;
  1257. }
  1258. call_user_func_array(array($this,$scope),(array)$params);
  1259. }
  1260. }
  1261. if(isset($c) || ($c=$this->getDbCriteria(false))!==null)
  1262. {
  1263. $c->mergeWith($criteria);
  1264. $criteria=$c;
  1265. $this->_c=null;
  1266. }
  1267. }
  1268. /**
  1269. * Returns the table alias to be used by the find methods.
  1270. * In relational queries, the returned table alias may vary according to
  1271. * the corresponding relation declaration. Also, the default table alias
  1272. * set by {@link setTableAlias} may be overridden by the applied scopes.
  1273. * @param boolean $quote whether to quote the alias name
  1274. * @param boolean $checkScopes whether to check if a table alias is defined in the applied scopes so far.
  1275. * This parameter must be set false when calling this method in {@link defaultScope}.
  1276. * An infinite loop would be formed otherwise.
  1277. * @return string the default table alias
  1278. * @since 1.1.1
  1279. */
  1280. public function getTableAlias($quote=false, $checkScopes=true)
  1281. {
  1282. if($checkScopes && ($criteria=$this->getDbCriteria(false))!==null && $criteria->alias!='')
  1283. $alias=$criteria->alias;
  1284. else
  1285. $alias=$this->_alias;
  1286. return $quote ? $this->getDbConnection()->getSchema()->quoteTableName($alias) : $alias;
  1287. }
  1288. /**
  1289. * Sets the table alias to be used in queries.
  1290. * @param string $alias the table alias to be used in queries. The alias should NOT be quoted.
  1291. * @since 1.1.3
  1292. */
  1293. public function setTableAlias($alias)
  1294. {
  1295. $this->_alias=$alias;
  1296. }
  1297. /**
  1298. * Finds a single active record with the specified condition.
  1299. * @param mixed $condition query condition or criteria.
  1300. * If a string, it is treated as query condition (the WHERE clause);
  1301. * If an array, it is treated as the initial values for constructing a {@link CDbCriteria} object;
  1302. * Otherwise, it should be an instance of {@link CDbCriteria}.
  1303. * @param array $params parameters to be bound to an SQL statement.
  1304. * This is only used when the first parameter is a string (query condition).
  1305. * In other cases, please use {@link CDbCriteria::params} to set parameters.
  1306. * @return CActiveRecord the record found. Null if no record is found.
  1307. */
  1308. public function find($condition='',$params=array())
  1309. {
  1310. Yii::trace(get_class($this).'.find()','system.db.ar.CActiveRecord');
  1311. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  1312. return $this->query($criteria);
  1313. }
  1314. /**
  1315. * Finds all active records satisfying the specified condition.
  1316. * See {@link find()} for detailed explanation about $condition and $params.
  1317. * @param mixed $condition query condition or criteria.
  1318. * @param array $params parameters to be bound to an SQL statement.
  1319. * @return array list of active records satisfying the specified condition. An empty array is returned if none is found.
  1320. */
  1321. public function findAll($condition='',$params=array())
  1322. {
  1323. Yii::trace(get_class($this).'.findAll()','system.db.ar.CActiveRecord');
  1324. $criteria=$this->getCommandBuilder()->createCriteria($condition,$params);
  1325. return $this->query($criteria,true);
  1326. }
  1327. /**
  1328. * Finds a single active record with the specified primary key.
  1329. * See {@link find()} for detailed explanation about $condition and $params.
  1330. * @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).
  1331. * @param mixed $condition query condition or criteria.
  1332. * @param array $params parameters to be bound to an SQL statement.
  1333. * @return CActiveRecord the record found. Null if none is found.
  1334. */
  1335. public function findByPk($pk,$condition='',$params=array())
  1336. {
  1337. Yii::trace(get_class($this).'.findByPk()','system.db.ar.CActiveRecord');
  1338. $prefix=$this->getTableAlias(true).'.';
  1339. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  1340. return $this->query($criteria);
  1341. }
  1342. /**
  1343. * Finds all active records with the specified primary keys.
  1344. * See {@link find()} for detailed explanation about $condition and $params.
  1345. * @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).
  1346. * @param mixed $condition query condition or criteria.
  1347. * @param array $params parameters to be bound to an SQL statement.
  1348. * @return array the records found. An empty array is returned if none is found.
  1349. */
  1350. public function findAllByPk($pk,$condition='',$params=array())
  1351. {
  1352. Yii::trace(get_class($this).'.findAllByPk()','system.db.ar.CActiveRecord');
  1353. $prefix=$this->getTableAlias(true).'.';
  1354. $criteria=$this->getCommandBuilder()->createPkCriteria($this->getTableSchema(),$pk,$condition,$params,$prefix);
  1355. return $this->query($criteria,true);
  1356. }
  1357. /**
  1358. * Finds a si