PageRenderTime 32ms CodeModel.GetById 25ms 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
  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 (indexed by attribute names) that the active records should match.
  1348. * Since version 1.0.8, an attribute value can be an array which will be used to generate an IN condition.
  1349. * @param mixed $condition query condition or criteria.
  1350. * @param array $params parameters to be bound to an SQL statement.
  1351. * @return array the records found. An empty array is returned if none is found.
  1352. */
  1353. public function findAllByAttributes($attributes,$condition='',$params=array())
  1354. {
  1355. Yii::trace(get_class($this).'.findAllByAttributes()','system.db.ar.CActiveRecord');
  1356. $prefix=$this->getTableAlias(true).'.';
  1357. $criteria=$this->getCommandBuilder()->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  1358. return $this->query($criteria,true);
  1359. }
  1360. /**
  1361. * Finds a single active record with the specified SQL statement.
  1362. * @param string $sql the SQL statement
  1363. * @param array $params parameters to be bound to the SQL statement
  1364. * @return CActiveRecord the record found. Null if none is found.
  1365. */
  1366. public function findBySql($sql,$params=array())
  1367. {
  1368. Yii::trace(get_class($this).'.findBySql()','system.db.ar.CActiveRecord');
  1369. $this->beforeFind();
  1370. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  1371. {
  1372. $this->_c=null;
  1373. $finder=new CActiveFinder($this,$criteria->with);
  1374. return $finder->findBySql($sql,$params);
  1375. }
  1376. else
  1377. {
  1378. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  1379. return $this->populateRecord($command->queryRow());
  1380. }
  1381. }
  1382. /**
  1383. * Finds all active records using the specified SQL statement.
  1384. * @param string $sql the SQL statement
  1385. * @param array $params parameters to be bound to the SQL statement
  1386. * @return array the records found. An empty array is returned if none is found.
  1387. */
  1388. public function findAllBySql($sql,$params=array())
  1389. {
  1390. Yii::trace(get_class($this).'.findAllBySql()','system.db.ar.CActiveRecord');
  1391. $this->beforeFind();
  1392. if(($criteria=$this->getDbCriteria(false))!==null && !empty($criteria->with))
  1393. {
  1394. $this->_c=null;
  1395. $finder=new CActiveFinder($this,$criteria->with);
  1396. return $finder->findAllBySql($sql,$params);
  1397. }
  1398. else
  1399. {
  1400. $command=$this->getCommandBuilder()->createSqlCommand($sql,$params);
  1401. return $this->populateRecords($command->queryAll());
  1402. }
  1403. }
  1404. /**
  1405. * Finds the number of rows satisfying the specified query condition.
  1406. * See {@link find()} for detailed explanation about $condition and $params.
  1407. * @param mixed $condition query condition or criteria.
  1408. * @param array $params parameters to be bound to an SQL statement.
  1409. * @return string the number of rows satisfying the specified query condition. Note: type is string to keep max. precision.
  1410. */
  1411. public function count($condition='',$params=array())
  1412. {
  1413. Yii::trace(get_class($this).'.count()','system.db.ar.CActiveRecord');
  1414. $builder=$this->getCommandBuilder();
  1415. $criteria=$builder->createCriteria($condition,$params);
  1416. $this->applyScopes($criteria);
  1417. if(empty($criteria->with))
  1418. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  1419. else
  1420. {
  1421. $finder=new CActiveFinder($this,$criteria->with);
  1422. return $finder->count($criteria);
  1423. }
  1424. }
  1425. /**
  1426. * Finds the number of rows that have the specified attribute values.
  1427. * See {@link find()} for detailed explanation about $condition and $params.
  1428. * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match.
  1429. * An attribute value can be an array which will be used to generate an IN condition.
  1430. * @param mixed $condition query condition or criteria.
  1431. * @param array $params parameters to be bound to an SQL statement.
  1432. * @return string the number of rows satisfying the specified query condition. Note: type is string to keep max. precision.
  1433. * @since 1.1.4
  1434. */
  1435. public function countByAttributes($attributes,$condition='',$params=array())
  1436. {
  1437. Yii::trace(get_class($this).'.countByAttributes()','system.db.ar.CActiveRecord');
  1438. $prefix=$this->getTableAlias(true).'.';
  1439. $builder=$this->getCommandBuilder();
  1440. $criteria=$builder->createColumnCriteria($this->getTableSchema(),$attributes,$condition,$params,$prefix);
  1441. $this->applyScopes($criteria);
  1442. if(empty($criteria->with))
  1443. return $builder->createCountCommand($this->getTableSchema(),$criteria)->queryScalar();
  1444. else
  1445. {
  1446. $finder=new CActiveFinder($this,$criteria->with);
  1447. return $finder->count($criteria);
  1448. }
  1449. }
  1450. /**
  1451. * Finds the number of rows using the given SQL statement.
  1452. * This is equivalent to calling {@link CDbCommand::queryScalar} with the specified
  1453. * SQL statement and the parameters.
  1454. * @param string $sql the SQL statement
  1455. * @param array $params parameters to be bound to the SQL statement
  1456. * @return string the number of rows using the given SQL statement. Note: type is string to keep max. precision.
  1457. */
  1458. public function countBySql($sql,$params=array())
  1459. {
  1460. Yii::trace(get_class($this).'.countBySql()','system.db.ar.CActiveRecord');
  1461. return $this->getCommandBuilder()->createSqlCommand($sql,$params)->queryScalar();
  1462. }
  1463. /**
  1464. * Checks whether there is row satisfying the specified condition.
  1465. * See {@link find()} for detailed explanation about $condition and $params.
  1466. * @param mixed $condition query condition or criteria.
  1467. * @param array $params parameters to be bound to an SQL statement.
  1468. * @return boolean whether there is row satisfying the specified condition.
  1469. */
  1470. public function exists($condition='',$params=array())
  1471. {
  1472. Yii::trace(get_class($this).'.exists()','system.db.ar.CActiveRecord');
  1473. $builder=$this->getCommandBuilder();
  1474. $criteria=$builder->createCriteria($condition,$params);
  1475. $table=$this->getTableSchema();
  1476. $criteria->select='1';
  1477. $criteria->limit=1;
  1478. $this->applyScopes($criteria);
  1479. return $builder->createFindCommand($table,$criteria)->queryRow()!==false;
  1480. }
  1481. /**
  1482. * Specifies which related objects should be eagerly loaded.
  1483. * This method takes variable number of parameters. Each parameter specifies
  1484. * the name of a relation or child-relation. For example,
  1485. * <pre>
  1486. * // find all posts together with their author and comments
  1487. * Post::model()->with('author','comments')->findAll();
  1488. * // find all posts together with their author and the author's profile
  1489. * Post::model()->with('author','author.profile')->findAll();
  1490. * </pre>
  1491. * The relations should be declared in {@link relations()}.
  1492. *
  1493. * By default, the options specified in {@link relations()} will be used
  1494. * to do relational query. In order to customize the options on the fly,
  1495. * we should pass an array parameter to the with() method. The array keys
  1496. * are relation names, and the array values are the corresponding query options.
  1497. * For example,
  1498. * <pre>
  1499. * Post::model()->with(array(
  1500. * 'author'=>array('select'=>'id, name'),
  1501. * 'comments'=>array('condition'=>'approved=1', 'order'=>'create_time'),
  1502. * ))->findAll();
  1503. * </pre>
  1504. *
  1505. * Note, the possible parameters to this method have been changed since version 1.0.2.
  1506. * Previously, it was not possible to specify on-th-fly query options,
  1507. * and child-relations were specified as hierarchical arrays.
  1508. *
  1509. * @return CActiveRecord the AR object itself.
  1510. */
  1511. public function with()
  1512. {
  1513. if(func_num_args()>0)
  1514. {
  1515. $with=func_get_args();
  1516. if(is_array($with[0])) // the parameter is given as an array
  1517. $with=$with[0];
  1518. if(!empty($with))
  1519. $this->getDbCriteria()->mergeWith(array('with'=>$with));
  1520. }
  1521. return $this;
  1522. }
  1523. /**
  1524. * Sets {@link CDbCriteria::together} property to be true.
  1525. * This is only used in relational AR query. Please refer to {@link CDbCriteria::together}
  1526. * for more details.
  1527. * @return CActiveRecord the AR object itself
  1528. * @since 1.1.4
  1529. */
  1530. public function together()
  1531. {
  1532. $this->getDbCriteria()->together=true;
  1533. return $this;
  1534. }
  1535. /**
  1536. * Updates records with the specified primary key(s).
  1537. * See {@link find()} for detailed explanation about $condition and $params.
  1538. * Note, the attributes are not checked for safety and validation is NOT performed.
  1539. * @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).
  1540. * @param array $attributes list of attributes (name=>$value) to be updated
  1541. * @param mixed $condition query condition or criteria.
  1542. * @param array $params parameters to be bound to an SQL statement.
  1543. * @return integer the number of rows being updated
  1544. */
  1545. public function updateByPk($pk,$attributes,$condition='',$params=array())
  1546. {
  1547. Yii::trace(get_class($this).'.updateByPk()','system.db.ar.CActiveRecord');
  1548. $builder=$this->getCommandBuilder();
  1549. $table=$this->getTableSchema();
  1550. $criteria=$builder->createPkCriteria($table,$pk,$condition,$params);
  1551. $command=$builder->createUpdateCommand($table,$attributes,$criteria);
  1552. return $command->execute();
  1553. }
  1554. /**
  1555. * Updates records with the specified condition.
  1556. * See {@link find()} for detailed explanation about $condition and $params.
  1557. * Note, the attributes are not checked for safety and no validation is done.
  1558. * @param array $attributes list of attributes (name=>$value) to be updated
  1559. * @param mixed $condition query condition or criteria.
  1560. * @param array $params parameters to be bound to an SQL statement.
  1561. * @return integer the number of rows being updated
  1562. */
  1563. public function updateAll($attributes,$condition='',$params=array())
  1564. {
  1565. Yii::trace(get_class($this).'.updateAll()','system.db.ar.CActiveRecord');
  1566. $builder=$this->getCommandBuilder();
  1567. $criteria=$builder->createCriteria($condition,$params);
  1568. $command=$builder->createUpdateCommand($this->getTableSchema(),$attributes,$criteria);
  1569. return $command->execute();
  1570. }
  1571. /**
  1572. * Updates one or several counter columns.
  1573. * Note, this updates all rows of data unless a condition or criteria is specified.
  1574. * See {@link find()} for detailed explanation about $condition and $params.
  1575. * @param array $counters the counters to be updated (column name=>increment value)
  1576. * @param mixed $condition query condition or criteria.
  1577. * @param array $params parameters to be bound to an SQL statement.
  1578. * @return integer the number of rows being updated
  1579. */
  1580. public function updateCounters($counters,$condition='',$params=array())
  1581. {
  1582. Yii::trace(get_class($this).'.updateCounters()','system.db.ar.CActiveRecord');
  1583. $builder=$this->getCommandBuilder();
  1584. $criteria=$builder->createCriteria($condition,$params);
  1585. $command=$builder->createUpdateCounterCommand($this->getTableSchema(),$counters,$criteria);
  1586. return $command->execute();
  1587. }
  1588. /**
  1589. * Deletes rows with the specified primary key.
  1590. * See {@link find()} for detailed explanation about $condition and $params.
  1591. * @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).
  1592. * @param mixed $condition query condition or criteria.
  1593. * @param array $params parameters to be bound to an SQL statement.
  1594. * @return integer the number of rows deleted
  1595. */
  1596. public function deleteByPk($pk,$condition='',$params=array())
  1597. {
  1598. Yii::trace(get_class($this).'.deleteByPk()','system.db.ar.CActiveRecord');
  1599. $builder=$this->getCommandBuilder();
  1600. $criteria=$builder->createPkCriteria($this->getTableSchema(),$pk,$condition,$params);
  1601. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  1602. return $command->execute();
  1603. }
  1604. /**
  1605. * Deletes rows with the specified condition.
  1606. * See {@link find()} for detailed explanation about $condition and $params.
  1607. * @param mixed $condition query condition or criteria.
  1608. * @param array $params parameters to be bound to an SQL statement.
  1609. * @return integer the number of rows deleted
  1610. */
  1611. public function deleteAll($condition='',$params=array())
  1612. {
  1613. Yii::trace(get_class($this).'.deleteAll()','system.db.ar.CActiveRecord');
  1614. $builder=$this->getCommandBuilder();
  1615. $criteria=$builder->createCriteria($condition,$params);
  1616. $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
  1617. return $command->execute();
  1618. }
  1619. /**
  1620. * Deletes rows which match the specified attribute values.
  1621. * See {@link find()} for detailed explanation about $condition and $params.
  1622. * @param array $attributes list of attribute values (indexed by attribute names) that the active records should match.
  1623. * Since version 1.0.8, an attribute value can be an array which will be used to generate an IN condition.
  1624. * @param mixed $condition query condition or criteria.
  1625. * @param array $params parameters to be bound to an SQL statement.
  1626. * @return integer number of rows affected by the execution.
  1627. * @since 1.0.9
  1628. */
  1629. public function deleteAllByAttributes($attributes,$condition='',$params=array())
  1630. {
  1631. Yii::trace(get_class($this).'.deleteAllByAttributes()','system.db.ar.CActiveRecord');
  1632. $builder=$this->getCommandBuilder();
  1633. $table=$this->getTableSchema();
  1634. $criteria=$builder->createColumnCriteria($table,$attributes,$condition,$params);
  1635. $command=$builder->createDeleteCommand($table,$criteria);
  1636. return $command->execute();
  1637. }
  1638. /**
  1639. * Creates an active record with the given attributes.
  1640. * This method is internally used by the find methods.
  1641. * @param array $attributes attribute values (column name=>column value)
  1642. * @param boolean $callAfterFind whether to call {@link afterFind} after the record is populated.
  1643. * This parameter is added in version 1.0.3.
  1644. * @return CActiveRecord the newly created active record. The class of the object is the same as the model class.
  1645. * Null is returned if the input data is false.
  1646. */
  1647. public function populateRecord($attributes,$callAfterFind=true)
  1648. {
  1649. if($attributes!==false)
  1650. {
  1651. $record=$this->instantiate($attributes);
  1652. $record->setScenario('update');
  1653. $record->init();
  1654. $md=$record->getMetaData();
  1655. foreach($attributes as $name=>$value)
  1656. {
  1657. if(property_exists($record,$name))
  1658. $record->$name=$value;
  1659. else if(isset($md->columns[$name]))
  1660. $record->_attributes[$name]=$value;
  1661. }
  1662. $record->_pk=$record->getPrimaryKey();
  1663. $record->attachBehaviors($record->behaviors());
  1664. if($callAfterFind)
  1665. $record->afterFind();
  1666. return $record;
  1667. }
  1668. else
  1669. return null;
  1670. }
  1671. /**
  1672. * Creates a list of active records based on the input data.
  1673. * This method is internally used by the find methods.
  1674. * @param array $data list of attribute values for the active records.
  1675. * @param boolean $callAfterFind whether to call {@link afterFind} after each record is populated.
  1676. * This parameter is added in version 1.0.3.
  1677. * @param string $index the name of the attribute whose value will be used as indexes of the query result array.
  1678. * If null, it means the array will be indexed by zero-based integers.
  1679. * @return array list of active records.
  1680. */
  1681. public function populateRecords($data,$callAfterFind=true,$index=null)
  1682. {
  1683. $records=array();
  1684. foreach($data as $attributes)
  1685. {
  1686. if(($record=$this->populateRecord($attributes,$callAfterFind))!==null)
  1687. {
  1688. if($index===null)
  1689. $records[]=$record;
  1690. else
  1691. $records[$record->$index]=$record;
  1692. }
  1693. }
  1694. return $records;
  1695. }
  1696. /**
  1697. * Creates an active record instance.
  1698. * This method is called by {@link populateRecord} and {@link populateRecords}.
  1699. * You may override this method if the instance being created
  1700. * depends the attributes that are to be populated to the record.
  1701. * For example, by creating a record based on the value of a column,
  1702. * you may implement the so-called single-table inheritance mapping.
  1703. * @param array $attributes list of attribute values for the active records.
  1704. * @return CActiveRecord the active record
  1705. * @since 1.0.2
  1706. */
  1707. protected function instantiate($attributes)
  1708. {
  1709. $class=get_class($this);
  1710. $model=new $class(null);
  1711. return $model;
  1712. }
  1713. /**
  1714. * Returns whether there is an element at the specified offset.
  1715. * This method is required by the interface ArrayAccess.
  1716. * @param mixed $offset the offset to check on
  1717. * @return boolean
  1718. * @since 1.0.2
  1719. */
  1720. public function offsetExists($offset)
  1721. {
  1722. return $this->__isset($offset);
  1723. }
  1724. }
  1725. /**
  1726. * CBaseActiveRelation is the base class for all active relations.
  1727. * @author Qiang Xue <qiang.xue@gmail.com>
  1728. * @version $Id: CActiveRecord.php 3102 2011-03-22 17:38:13Z qiang.xue $
  1729. * @package system.db.ar
  1730. * @since 1.0.4
  1731. */
  1732. class CBaseActiveRelation extends CComponent
  1733. {
  1734. /**
  1735. * @var string name of the related object
  1736. */
  1737. public $name;
  1738. /**
  1739. * @var string name of the related active record class
  1740. */
  1741. public $className;
  1742. /**
  1743. * @var string the foreign key in this relation
  1744. */
  1745. public $foreignKey;
  1746. /**
  1747. * @var mixed list of column names (an array, or a string of names separated by commas) to be selected.
  1748. * Do not quote or prefix the column names unless they are used in an expression.
  1749. * In that case, you should prefix the column names with 'relationName.'.
  1750. */
  1751. public $select='*';
  1752. /**
  1753. * @var string WHERE clause. For {@link CActiveRelation} descendant classes, column names
  1754. * referenced in the condition should be disambiguated with prefix 'relationName.'.
  1755. */
  1756. public $condition='';
  1757. /**
  1758. * @var array the parameters that are to be bound to the condition.
  1759. * The keys are parameter placeholder names, and the values are parameter values.
  1760. */
  1761. public $params=array();
  1762. /**
  1763. * @var string GROUP BY clause. For {@link CActiveRelation} descendant classes, column names
  1764. * referenced in this property should be disambiguated with prefix 'relationName.'.
  1765. */
  1766. public $group='';
  1767. /**
  1768. * @var string how to join with other tables. This refers to the JOIN clause in an SQL statement.
  1769. * For example, <code>'LEFT JOIN users ON users.id=authorID'</code>.
  1770. * @since 1.1.3
  1771. */
  1772. public $join='';
  1773. /**
  1774. * @var string HAVING clause. For {@link CActiveRelation} descendant classes, column names
  1775. * referenced in this property should be disambiguated with prefix 'relationName.'.
  1776. */
  1777. public $having='';
  1778. /**
  1779. * @var string ORDER BY clause. For {@link CActiveRelation} descendant classes, column names
  1780. * referenced in this property should be disambiguated with prefix 'relationName.'.
  1781. */
  1782. public $order='';
  1783. /**
  1784. * Constructor.
  1785. * @param string $name name of the relation
  1786. * @param string $className name of the related active record class
  1787. * @param string $foreignKey foreign key for this relation
  1788. * @param array $options additional options (name=>value). The keys must be the property names of this class.
  1789. */
  1790. public function __construct($name,$className,$foreignKey,$options=array())
  1791. {
  1792. $this->name=$name;
  1793. $this->className=$className;
  1794. $this->foreignKey=$foreignKey;
  1795. foreach($options as $name=>$value)
  1796. $this->$name=$value;
  1797. }
  1798. /**
  1799. * Merges this relation with a criteria specified dynamically.
  1800. * @param array $criteria the dynamically specified criteria
  1801. * @param boolean $fromScope whether the criteria to be merged is from scopes
  1802. * @since 1.0.5
  1803. */
  1804. public function mergeWith($criteria,$fromScope=false)
  1805. {
  1806. if($criteria instanceof CDbCriteria)
  1807. $criteria=$criteria->toArray();
  1808. if(isset($criteria['select']) && $this->select!==$criteria['select'])
  1809. {
  1810. if($this->select==='*')
  1811. $this->select=$criteria['select'];
  1812. else if($criteria['select']!=='*')
  1813. {
  1814. $select1=is_string($this->select)?preg_split('/\s*,\s*/',trim($this->select),-1,PREG_SPLIT_NO_EMPTY):$this->select;
  1815. $select2=is_string($criteria['select'])?preg_split('/\s*,\s*/',trim($criteria['select']),-1,PREG_SPLIT_NO_EMPTY):$criteria['select'];
  1816. $this->select=array_merge($select1,array_diff($select2,$select1));
  1817. }
  1818. }
  1819. if(isset($criteria['condition']) && $this->condition!==$criteria['condition'])
  1820. {
  1821. if($this->condition==='')
  1822. $this->condition=$criteria['condition'];
  1823. else if($criteria['condition']!=='')
  1824. $this->condition="({$this->condition}) AND ({$criteria['condition']})";
  1825. }
  1826. if(isset($criteria['params']) && $this->params!==$criteria['params'])
  1827. $this->params=array_merge($this->params,$criteria['params']);
  1828. if(isset($criteria['order']) && $this->order!==$criteria['order'])
  1829. {
  1830. if($this->order==='')
  1831. $this->order=$criteria['order'];
  1832. else if($criteria['order']!=='')
  1833. $this->order=$criteria['order'].', '.$this->order;
  1834. }
  1835. if(isset($criteria['group']) && $this->group!==$criteria['group'])
  1836. {
  1837. if($this->group==='')
  1838. $this->group=$criteria['group'];
  1839. else if($criteria['group']!=='')
  1840. $this->group.=', '.$criteria['group'];
  1841. }
  1842. if(isset($criteria['join']) && $this->join!==$criteria['join'])
  1843. {
  1844. if($this->join==='')
  1845. $this->join=$criteria['join'];
  1846. else if($criteria['join']!=='')
  1847. $this->join.=' '.$criteria['join'];
  1848. }
  1849. if(isset($criteria['having']) && $this->having!==$criteria['having'])
  1850. {
  1851. if($this->having==='')
  1852. $this->having=$criteria['having'];
  1853. else if($criteria['having']!=='')
  1854. $this->having="({$this->having}) AND ({$criteria['having']})";
  1855. }
  1856. }
  1857. }
  1858. /**
  1859. * CStatRelation represents a statistical relational query.
  1860. * @author Qiang Xue <qiang.xue@gmail.com>
  1861. * @version $Id: CActiveRecord.php 3102 2011-03-22 17:38:13Z qiang.xue $
  1862. * @package system.db.ar
  1863. * @since 1.0.4
  1864. */
  1865. class CStatRelation extends CBaseActiveRelation
  1866. {
  1867. /**
  1868. * @var string the statistical expression. Defaults to 'COUNT(*)', meaning
  1869. * the count of child objects.
  1870. */
  1871. public $select='COUNT(*)';
  1872. /**
  1873. * @var mixed the default value to be assigned to those records that do not
  1874. * receive a statistical query result. Defaults to 0.
  1875. */
  1876. public $defaultValue=0;
  1877. /**
  1878. * Merges this relation with a criteria specified dynamically.
  1879. * @param array $criteria the dynamically specified criteria
  1880. * @param boolean $fromScope whether the criteria to be merged is from scopes
  1881. * @since 1.0.5
  1882. */
  1883. public function mergeWith($criteria,$fromScope=false)
  1884. {
  1885. if($criteria instanceof CDbCriteria)
  1886. $criteria=$criteria->toArray();
  1887. parent::mergeWith($criteria,$fromScope);
  1888. if(isset($criteria['defaultValue']))
  1889. $this->defaultValue=$criteria['defaultValue'];
  1890. }
  1891. }
  1892. /**
  1893. * CActiveRelation is the base class for representing active relations that bring back related objects.
  1894. * @author Qiang Xue <qiang.xue@gmail.com>
  1895. * @version $Id: CActiveRecord.php 3102 2011-03-22 17:38:13Z qiang.xue $
  1896. * @package system.db.ar
  1897. * @since 1.0
  1898. */
  1899. class CActiveRelation extends CBaseActiveRelation
  1900. {
  1901. /**
  1902. * @var string join type. Defaults to 'LEFT OUTER JOIN'.
  1903. */
  1904. public $joinType='LEFT OUTER JOIN';
  1905. /**
  1906. * @var string ON clause. The condition specified here will be appended to the joining condition using AND operator.
  1907. * @since 1.0.2
  1908. */
  1909. public $on='';
  1910. /**
  1911. * @var string the alias for the table that this relation refers to. Defaults to null, meaning
  1912. * the alias will be the same as the relation name.
  1913. * @since 1.0.1
  1914. */
  1915. public $alias;
  1916. /**
  1917. * @var string|array specifies which related objects should be eagerly loaded when this related object is lazily loaded.
  1918. * For more details about this property, see {@link CActiveRecord::with()}.
  1919. */
  1920. public $with=array();
  1921. /**
  1922. * @var boolean whether this table should be joined with the primary table.
  1923. * When setting this property to be false, the table associated with this relation will
  1924. * appear in a separate JOIN statement.
  1925. * If this property is set true, then the corresponding table will ALWAYS be joined together
  1926. * with the primary table, no matter the primary table is limited or not.
  1927. * If this property is not set, the corresponding table will be joined with the primary table
  1928. * only when the primary table is not limited.
  1929. */
  1930. public $together;
  1931. /**
  1932. * Merges this relation with a criteria specified dynamically.
  1933. * @param array $criteria the dynamically specified criteria
  1934. * @param boolean $fromScope whether the criteria to be merged is from scopes
  1935. * @since 1.0.5
  1936. */
  1937. public function mergeWith($criteria,$fromScope=false)
  1938. {
  1939. if($criteria instanceof CDbCriteria)
  1940. $criteria=$criteria->toArray();
  1941. if($fromScope)
  1942. {
  1943. if(isset($criteria['condition']) && $this->on!==$criteria['condition'])
  1944. {
  1945. if($this->on==='')
  1946. $this->on=$criteria['condition'];
  1947. else if($criteria['condition']!=='')
  1948. $this->on="({$this->on}) AND ({$criteria['condition']})";
  1949. }
  1950. unset($criteria['condition']);
  1951. }
  1952. parent::mergeWith($criteria);
  1953. if(isset($criteria['joinType']))
  1954. $this->joinType=$criteria['joinType'];
  1955. if(isset($criteria['on']) && $this->on!==$criteria['on'])
  1956. {
  1957. if($this->on==='')
  1958. $this->on=$criteria['on'];
  1959. else if($criteria['on']!=='')
  1960. $this->on="({$this->on}) AND ({$criteria['on']})";
  1961. }
  1962. if(isset($criteria['with']))
  1963. $this->with=$criteria['with'];
  1964. if(isset($criteria['alias']))
  1965. $this->alias=$criteria['alias'];
  1966. if(isset($criteria['together']))
  1967. $this->together=$criteria['together'];
  1968. }
  1969. }
  1970. /**
  1971. * CBelongsToRelation represents the parameters specifying a BELONGS_TO relation.
  1972. * @author Qiang Xue <qiang.xue@gmail.com>
  1973. * @version $Id: CActiveRecord.php 3102 2011-03-22 17:38:13Z qiang.xue $
  1974. * @package system.db.ar
  1975. * @since 1.0
  1976. */
  1977. class CBelongsToRelation extends CActiveRelation
  1978. {
  1979. }
  1980. /**
  1981. * CHasOneRelation represents the parameters specifying a HAS_ONE relation.
  1982. * @author Qiang Xue <qiang.xue@gmail.com>
  1983. * @version $Id: CActiveRecord.php 3102 2011-03-22 17:38:13Z qiang.xue $
  1984. * @package system.db.ar
  1985. * @since 1.0
  1986. */
  1987. class CHasOneRelation extends CActiveRelation
  1988. {
  1989. /**
  1990. * @var string the name of the relation that should be used as the bridge to this relation.
  1991. * Deafults to null, meaning don't use any bridge.
  1992. * @since 1.1.7
  1993. */
  1994. public $through;
  1995. }
  1996. /**
  1997. * CHasManyRelation represents the parameters specifying a HAS_MANY relation.
  1998. * @author Qiang Xue <qiang.xue@gmail.com>
  1999. * @version $Id: CActiveRecord.php 3102 2011-03-22 17:38:13Z qiang.xue $
  2000. * @package system.db.ar
  2001. * @since 1.0
  2002. */
  2003. class CHasManyRelation extends CActiveRelation
  2004. {
  2005. /**
  2006. * @var integer limit of the rows to be selected. It is effective only for lazy loading this related object. Defaults to -1, meaning no limit.
  2007. */
  2008. public $limit=-1;
  2009. /**
  2010. * @var integer offset of the rows to be selected. It is effective only for lazy loading this related object. Defaults to -1, meaning no offset.
  2011. */
  2012. public $offset=-1;
  2013. /**
  2014. * @var string the name of the column that should be used as the key for storing related objects.
  2015. * Defaults to null, meaning using zero-based integer IDs.
  2016. * @since 1.0.7
  2017. */
  2018. public $index;
  2019. /**
  2020. * @var string the name of the relation that should be used as the bridge to this relation.
  2021. * Deafults to null, meaning don't use any bridge.
  2022. * @since 1.1.7
  2023. */
  2024. public $through;
  2025. /**
  2026. * Merges this relation with a criteria specified dynamically.
  2027. * @param array $criteria the dynamically specified criteria
  2028. * @param boolean $fromScope whether the criteria to be merged is from scopes
  2029. * @since 1.0.5
  2030. */
  2031. public function mergeWith($criteria,$fromScope=false)
  2032. {
  2033. if($criteria instanceof CDbCriteria)
  2034. $criteria=$criteria->toArray();
  2035. parent::mergeWith($criteria,$fromScope);
  2036. if(isset($criteria['limit']) && $criteria['limit']>0)
  2037. $this->limit=$criteria['limit'];
  2038. if(isset($criteria['offset']) && $criteria['offset']>=0)
  2039. $this->offset=$criteria['offset'];
  2040. if(isset($criteria['index']))
  2041. $this->index=$criteria['index'];
  2042. }
  2043. }
  2044. /**
  2045. * CManyManyRelation represents the parameters specifying a MANY_MANY relation.
  2046. * @author Qiang Xue <qiang.xue@gmail.com>
  2047. * @version $Id: CActiveRecord.php 3102 2011-03-22 17:38:13Z qiang.xue $
  2048. * @package system.db.ar
  2049. * @since 1.0
  2050. */
  2051. class CManyManyRelation extends CHasManyRelation
  2052. {
  2053. }
  2054. /**
  2055. * CActiveRecordMetaData represents the meta-data for an Active Record class.
  2056. *
  2057. * @author Qiang Xue <qiang.xue@gmail.com>
  2058. * @version $Id: CActiveRecord.php 3102 2011-03-22 17:38:13Z qiang.xue $
  2059. * @package system.db.ar
  2060. * @since 1.0
  2061. */
  2062. class CActiveRecordMetaData
  2063. {
  2064. /**
  2065. * @var CDbTableSchema the table schema information
  2066. */
  2067. public $tableSchema;
  2068. /**
  2069. * @var array table columns
  2070. */
  2071. public $columns;
  2072. /**
  2073. * @var array list of relations
  2074. */
  2075. public $relations=array();
  2076. /**
  2077. * @var array attribute default values
  2078. */
  2079. public $attributeDefaults=array();
  2080. private $_model;
  2081. /**
  2082. * Constructor.
  2083. * @param CActiveRecord $model the model instance
  2084. */
  2085. public function __construct($model)
  2086. {
  2087. $this->_model=$model;
  2088. $tableName=$model->tableName();
  2089. if(($table=$model->getDbConnection()->getSchema()->getTable($tableName))===null)
  2090. throw new CDbException(Yii::t('yii','The table "{table}" for active record class "{class}" cannot be found in the database.',
  2091. array('{class}'=>get_class($model),'{table}'=>$tableName)));
  2092. if($table->primaryKey===null)
  2093. $table->primaryKey=$model->primaryKey();
  2094. $this->tableSchema=$table;
  2095. $this->columns=$table->columns;
  2096. foreach($table->columns as $name=>$column)
  2097. {
  2098. if(!$column->isPrimaryKey && $column->defaultValue!==null)
  2099. $this->attributeDefaults[$name]=$column->defaultValue;
  2100. }
  2101. foreach($model->relations() as $name=>$config)
  2102. {
  2103. $this->addRelation($name,$config);
  2104. }
  2105. }
  2106. /**
  2107. * Adds a relation.
  2108. *
  2109. * $config is an array with three elements:
  2110. * relation type, the related active record class and the foreign key.
  2111. *
  2112. * @throws CDbException
  2113. * @param string $name $name Name of the relation.
  2114. * @param array $config $config Relation parameters.
  2115. * @return void
  2116. * @since 1.1.2
  2117. */
  2118. public function addRelation($name,$config)
  2119. {
  2120. if(isset($config[0],$config[1],$config[2])) // relation class, AR class, FK
  2121. $this->relations[$name]=new $config[0]($name,$config[1],$config[2],array_slice($config,3));
  2122. else
  2123. throw new CDbException(Yii::t('yii','Active record "{class}" has an invalid configuration for relation "{relation}". It must specify the relation type, the related active record class and the foreign key.', array('{class}'=>get_class($this->_model),'{relation}'=>$name)));
  2124. }
  2125. /**
  2126. * Checks if there is a relation with specified name defined.
  2127. *
  2128. * @param string $name $name Name of the relation.
  2129. * @return boolean
  2130. * @since 1.1.2
  2131. */
  2132. public function hasRelation($name)
  2133. {
  2134. return isset($this->relations[$name]);
  2135. }
  2136. /**
  2137. * Deletes a relation with specified name.
  2138. *
  2139. * @param string $name $name
  2140. * @return void
  2141. * @since 1.1.2
  2142. */
  2143. public function removeRelation($name)
  2144. {
  2145. unset($this->relations[$name]);
  2146. }
  2147. }