PageRenderTime 121ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/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

Large files files are truncated, but you can click here to view the full 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. * @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 $thi

Large files files are truncated, but you can click here to view the full file