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

/packages/yii-1.1.7.r3135/framework/db/ar/CActiveRecord.php

https://github.com/apptous-seb/gitplay
PHP | 2299 lines | 1087 code | 152 blank | 1060 comment | 202 complexity | 65635c30d36529da71c94f8040464f27 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, BSD-2-Clause

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

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