CActiveRecord.php 86 KB

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