CActiveRecord.php 85 KB

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