BaseActiveRecord.php 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\db;
  8. use Yii;
  9. use yii\base\InvalidArgumentException;
  10. use yii\base\InvalidCallException;
  11. use yii\base\InvalidConfigException;
  12. use yii\base\InvalidParamException;
  13. use yii\base\Model;
  14. use yii\base\ModelEvent;
  15. use yii\base\NotSupportedException;
  16. use yii\base\UnknownMethodException;
  17. use yii\helpers\ArrayHelper;
  18. /**
  19. * ActiveRecord is the base class for classes representing relational data in terms of objects.
  20. *
  21. * See [[\yii\db\ActiveRecord]] for a concrete implementation.
  22. *
  23. * @property-read array $dirtyAttributes The changed attribute values (name-value pairs).
  24. * @property bool $isNewRecord Whether the record is new and should be inserted when calling [[save()]].
  25. * @property array $oldAttributes The old attribute values (name-value pairs). Note that the type of this
  26. * property differs in getter and setter. See [[getOldAttributes()]] and [[setOldAttributes()]] for details.
  27. * @property-read mixed $oldPrimaryKey The old primary key value. An array (column name => column value) is
  28. * returned if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be
  29. * returned if the key value is null).
  30. * @property-read mixed $primaryKey The primary key value. An array (column name => column value) is returned
  31. * if the primary key is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned
  32. * if the key value is null).
  33. * @property-read array $relatedRecords An array of related records indexed by relation names.
  34. *
  35. * @author Qiang Xue <qiang.xue@gmail.com>
  36. * @author Carsten Brandt <mail@cebe.cc>
  37. * @since 2.0
  38. */
  39. abstract class BaseActiveRecord extends Model implements ActiveRecordInterface
  40. {
  41. /**
  42. * @event Event an event that is triggered when the record is initialized via [[init()]].
  43. */
  44. const EVENT_INIT = 'init';
  45. /**
  46. * @event Event an event that is triggered after the record is created and populated with query result.
  47. */
  48. const EVENT_AFTER_FIND = 'afterFind';
  49. /**
  50. * @event ModelEvent an event that is triggered before inserting a record.
  51. * You may set [[ModelEvent::isValid]] to be `false` to stop the insertion.
  52. */
  53. const EVENT_BEFORE_INSERT = 'beforeInsert';
  54. /**
  55. * @event AfterSaveEvent an event that is triggered after a record is inserted.
  56. */
  57. const EVENT_AFTER_INSERT = 'afterInsert';
  58. /**
  59. * @event ModelEvent an event that is triggered before updating a record.
  60. * You may set [[ModelEvent::isValid]] to be `false` to stop the update.
  61. */
  62. const EVENT_BEFORE_UPDATE = 'beforeUpdate';
  63. /**
  64. * @event AfterSaveEvent an event that is triggered after a record is updated.
  65. */
  66. const EVENT_AFTER_UPDATE = 'afterUpdate';
  67. /**
  68. * @event ModelEvent an event that is triggered before deleting a record.
  69. * You may set [[ModelEvent::isValid]] to be `false` to stop the deletion.
  70. */
  71. const EVENT_BEFORE_DELETE = 'beforeDelete';
  72. /**
  73. * @event Event an event that is triggered after a record is deleted.
  74. */
  75. const EVENT_AFTER_DELETE = 'afterDelete';
  76. /**
  77. * @event Event an event that is triggered after a record is refreshed.
  78. * @since 2.0.8
  79. */
  80. const EVENT_AFTER_REFRESH = 'afterRefresh';
  81. /**
  82. * @var array attribute values indexed by attribute names
  83. */
  84. private $_attributes = [];
  85. /**
  86. * @var array|null old attribute values indexed by attribute names.
  87. * This is `null` if the record [[isNewRecord|is new]].
  88. */
  89. private $_oldAttributes;
  90. /**
  91. * @var array related models indexed by the relation names
  92. */
  93. private $_related = [];
  94. /**
  95. * @var array relation names indexed by their link attributes
  96. */
  97. private $_relationsDependencies = [];
  98. /**
  99. * {@inheritdoc}
  100. * @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches.
  101. */
  102. public static function findOne($condition)
  103. {
  104. return static::findByCondition($condition)->one();
  105. }
  106. /**
  107. * {@inheritdoc}
  108. * @return static[] an array of ActiveRecord instances, or an empty array if nothing matches.
  109. */
  110. public static function findAll($condition)
  111. {
  112. return static::findByCondition($condition)->all();
  113. }
  114. /**
  115. * Finds ActiveRecord instance(s) by the given condition.
  116. * This method is internally called by [[findOne()]] and [[findAll()]].
  117. * @param mixed $condition please refer to [[findOne()]] for the explanation of this parameter
  118. * @return ActiveQueryInterface the newly created [[ActiveQueryInterface|ActiveQuery]] instance.
  119. * @throws InvalidConfigException if there is no primary key defined
  120. * @internal
  121. */
  122. protected static function findByCondition($condition)
  123. {
  124. $query = static::find();
  125. if (!ArrayHelper::isAssociative($condition) && !$condition instanceof ExpressionInterface) {
  126. // query by primary key
  127. $primaryKey = static::primaryKey();
  128. if (isset($primaryKey[0])) {
  129. // if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values
  130. $condition = [$primaryKey[0] => is_array($condition) ? array_values($condition) : $condition];
  131. } else {
  132. throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
  133. }
  134. }
  135. return $query->andWhere($condition);
  136. }
  137. /**
  138. * Updates the whole table using the provided attribute values and conditions.
  139. *
  140. * For example, to change the status to be 1 for all customers whose status is 2:
  141. *
  142. * ```php
  143. * Customer::updateAll(['status' => 1], 'status = 2');
  144. * ```
  145. *
  146. * @param array $attributes attribute values (name-value pairs) to be saved into the table
  147. * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
  148. * Please refer to [[Query::where()]] on how to specify this parameter.
  149. * @return int the number of rows updated
  150. * @throws NotSupportedException if not overridden
  151. */
  152. public static function updateAll($attributes, $condition = '')
  153. {
  154. throw new NotSupportedException(__METHOD__ . ' is not supported.');
  155. }
  156. /**
  157. * Updates the whole table using the provided counter changes and conditions.
  158. *
  159. * For example, to increment all customers' age by 1,
  160. *
  161. * ```php
  162. * Customer::updateAllCounters(['age' => 1]);
  163. * ```
  164. *
  165. * @param array $counters the counters to be updated (attribute name => increment value).
  166. * Use negative values if you want to decrement the counters.
  167. * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
  168. * Please refer to [[Query::where()]] on how to specify this parameter.
  169. * @return int the number of rows updated
  170. * @throws NotSupportedException if not overrided
  171. */
  172. public static function updateAllCounters($counters, $condition = '')
  173. {
  174. throw new NotSupportedException(__METHOD__ . ' is not supported.');
  175. }
  176. /**
  177. * Deletes rows in the table using the provided conditions.
  178. * WARNING: If you do not specify any condition, this method will delete ALL rows in the table.
  179. *
  180. * For example, to delete all customers whose status is 3:
  181. *
  182. * ```php
  183. * Customer::deleteAll('status = 3');
  184. * ```
  185. *
  186. * @param string|array|null $condition the conditions that will be put in the WHERE part of the DELETE SQL.
  187. * Please refer to [[Query::where()]] on how to specify this parameter.
  188. * @return int the number of rows deleted
  189. * @throws NotSupportedException if not overridden.
  190. */
  191. public static function deleteAll($condition = null)
  192. {
  193. throw new NotSupportedException(__METHOD__ . ' is not supported.');
  194. }
  195. /**
  196. * Returns the name of the column that stores the lock version for implementing optimistic locking.
  197. *
  198. * Optimistic locking allows multiple users to access the same record for edits and avoids
  199. * potential conflicts. In case when a user attempts to save the record upon some staled data
  200. * (because another user has modified the data), a [[StaleObjectException]] exception will be thrown,
  201. * and the update or deletion is skipped.
  202. *
  203. * Optimistic locking is only supported by [[update()]] and [[delete()]].
  204. *
  205. * To use Optimistic locking:
  206. *
  207. * 1. Create a column to store the version number of each row. The column type should be `BIGINT DEFAULT 0`.
  208. * Override this method to return the name of this column.
  209. * 2. Ensure the version value is submitted and loaded to your model before any update or delete.
  210. * Or add [[\yii\behaviors\OptimisticLockBehavior|OptimisticLockBehavior]] to your model
  211. * class in order to automate the process.
  212. * 3. In the Web form that collects the user input, add a hidden field that stores
  213. * the lock version of the record being updated.
  214. * 4. In the controller action that does the data updating, try to catch the [[StaleObjectException]]
  215. * and implement necessary business logic (e.g. merging the changes, prompting stated data)
  216. * to resolve the conflict.
  217. *
  218. * @return string|null the column name that stores the lock version of a table row.
  219. * If `null` is returned (default implemented), optimistic locking will not be supported.
  220. */
  221. public function optimisticLock()
  222. {
  223. return null;
  224. }
  225. /**
  226. * {@inheritdoc}
  227. */
  228. public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
  229. {
  230. if (parent::canGetProperty($name, $checkVars, $checkBehaviors)) {
  231. return true;
  232. }
  233. try {
  234. return $this->hasAttribute($name);
  235. } catch (\Exception $e) {
  236. // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used
  237. return false;
  238. }
  239. }
  240. /**
  241. * {@inheritdoc}
  242. */
  243. public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
  244. {
  245. if (parent::canSetProperty($name, $checkVars, $checkBehaviors)) {
  246. return true;
  247. }
  248. try {
  249. return $this->hasAttribute($name);
  250. } catch (\Exception $e) {
  251. // `hasAttribute()` may fail on base/abstract classes in case automatic attribute list fetching used
  252. return false;
  253. }
  254. }
  255. /**
  256. * PHP getter magic method.
  257. * This method is overridden so that attributes and related objects can be accessed like properties.
  258. *
  259. * @param string $name property name
  260. * @throws InvalidArgumentException if relation name is wrong
  261. * @return mixed property value
  262. * @see getAttribute()
  263. */
  264. public function __get($name)
  265. {
  266. if (array_key_exists($name, $this->_attributes)) {
  267. return $this->_attributes[$name];
  268. }
  269. if ($this->hasAttribute($name)) {
  270. return null;
  271. }
  272. if (array_key_exists($name, $this->_related)) {
  273. return $this->_related[$name];
  274. }
  275. $value = parent::__get($name);
  276. if ($value instanceof ActiveQueryInterface) {
  277. $this->setRelationDependencies($name, $value);
  278. return $this->_related[$name] = $value->findFor($name, $this);
  279. }
  280. return $value;
  281. }
  282. /**
  283. * PHP setter magic method.
  284. * This method is overridden so that AR attributes can be accessed like properties.
  285. * @param string $name property name
  286. * @param mixed $value property value
  287. */
  288. public function __set($name, $value)
  289. {
  290. if ($this->hasAttribute($name)) {
  291. if (
  292. !empty($this->_relationsDependencies[$name])
  293. && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
  294. ) {
  295. $this->resetDependentRelations($name);
  296. }
  297. $this->_attributes[$name] = $value;
  298. } else {
  299. parent::__set($name, $value);
  300. }
  301. }
  302. /**
  303. * Checks if a property value is null.
  304. * This method overrides the parent implementation by checking if the named attribute is `null` or not.
  305. * @param string $name the property name or the event name
  306. * @return bool whether the property value is null
  307. */
  308. public function __isset($name)
  309. {
  310. try {
  311. return $this->__get($name) !== null;
  312. } catch (\Exception $t) {
  313. return false;
  314. } catch (\Throwable $e) {
  315. return false;
  316. }
  317. }
  318. /**
  319. * Sets a component property to be null.
  320. * This method overrides the parent implementation by clearing
  321. * the specified attribute value.
  322. * @param string $name the property name or the event name
  323. */
  324. public function __unset($name)
  325. {
  326. if ($this->hasAttribute($name)) {
  327. unset($this->_attributes[$name]);
  328. if (!empty($this->_relationsDependencies[$name])) {
  329. $this->resetDependentRelations($name);
  330. }
  331. } elseif (array_key_exists($name, $this->_related)) {
  332. unset($this->_related[$name]);
  333. } elseif ($this->getRelation($name, false) === null) {
  334. parent::__unset($name);
  335. }
  336. }
  337. /**
  338. * Declares a `has-one` relation.
  339. * The declaration is returned in terms of a relational [[ActiveQuery]] instance
  340. * through which the related record can be queried and retrieved back.
  341. *
  342. * A `has-one` relation means that there is at most one related record matching
  343. * the criteria set by this relation, e.g., a customer has one country.
  344. *
  345. * For example, to declare the `country` relation for `Customer` class, we can write
  346. * the following code in the `Customer` class:
  347. *
  348. * ```php
  349. * public function getCountry()
  350. * {
  351. * return $this->hasOne(Country::class, ['id' => 'country_id']);
  352. * }
  353. * ```
  354. *
  355. * Note that in the above, the 'id' key in the `$link` parameter refers to an attribute name
  356. * in the related class `Country`, while the 'country_id' value refers to an attribute name
  357. * in the current AR class.
  358. *
  359. * Call methods declared in [[ActiveQuery]] to further customize the relation.
  360. *
  361. * @param string $class the class name of the related record
  362. * @param array $link the primary-foreign key constraint. The keys of the array refer to
  363. * the attributes of the record associated with the `$class` model, while the values of the
  364. * array refer to the corresponding attributes in **this** AR class.
  365. * @return ActiveQueryInterface the relational query object.
  366. */
  367. public function hasOne($class, $link)
  368. {
  369. return $this->createRelationQuery($class, $link, false);
  370. }
  371. /**
  372. * Declares a `has-many` relation.
  373. * The declaration is returned in terms of a relational [[ActiveQuery]] instance
  374. * through which the related record can be queried and retrieved back.
  375. *
  376. * A `has-many` relation means that there are multiple related records matching
  377. * the criteria set by this relation, e.g., a customer has many orders.
  378. *
  379. * For example, to declare the `orders` relation for `Customer` class, we can write
  380. * the following code in the `Customer` class:
  381. *
  382. * ```php
  383. * public function getOrders()
  384. * {
  385. * return $this->hasMany(Order::class, ['customer_id' => 'id']);
  386. * }
  387. * ```
  388. *
  389. * Note that in the above, the 'customer_id' key in the `$link` parameter refers to
  390. * an attribute name in the related class `Order`, while the 'id' value refers to
  391. * an attribute name in the current AR class.
  392. *
  393. * Call methods declared in [[ActiveQuery]] to further customize the relation.
  394. *
  395. * @param string $class the class name of the related record
  396. * @param array $link the primary-foreign key constraint. The keys of the array refer to
  397. * the attributes of the record associated with the `$class` model, while the values of the
  398. * array refer to the corresponding attributes in **this** AR class.
  399. * @return ActiveQueryInterface the relational query object.
  400. */
  401. public function hasMany($class, $link)
  402. {
  403. return $this->createRelationQuery($class, $link, true);
  404. }
  405. /**
  406. * Creates a query instance for `has-one` or `has-many` relation.
  407. * @param string $class the class name of the related record.
  408. * @param array $link the primary-foreign key constraint.
  409. * @param bool $multiple whether this query represents a relation to more than one record.
  410. * @return ActiveQueryInterface the relational query object.
  411. * @since 2.0.12
  412. * @see hasOne()
  413. * @see hasMany()
  414. */
  415. protected function createRelationQuery($class, $link, $multiple)
  416. {
  417. /* @var $class ActiveRecordInterface */
  418. /* @var $query ActiveQuery */
  419. $query = $class::find();
  420. $query->primaryModel = $this;
  421. $query->link = $link;
  422. $query->multiple = $multiple;
  423. return $query;
  424. }
  425. /**
  426. * Populates the named relation with the related records.
  427. * Note that this method does not check if the relation exists or not.
  428. * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
  429. * @param ActiveRecordInterface|array|null $records the related records to be populated into the relation.
  430. * @see getRelation()
  431. */
  432. public function populateRelation($name, $records)
  433. {
  434. foreach ($this->_relationsDependencies as &$relationNames) {
  435. unset($relationNames[$name]);
  436. }
  437. $this->_related[$name] = $records;
  438. }
  439. /**
  440. * Check whether the named relation has been populated with records.
  441. * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
  442. * @return bool whether relation has been populated with records.
  443. * @see getRelation()
  444. */
  445. public function isRelationPopulated($name)
  446. {
  447. return array_key_exists($name, $this->_related);
  448. }
  449. /**
  450. * Returns all populated related records.
  451. * @return array an array of related records indexed by relation names.
  452. * @see getRelation()
  453. */
  454. public function getRelatedRecords()
  455. {
  456. return $this->_related;
  457. }
  458. /**
  459. * Returns a value indicating whether the model has an attribute with the specified name.
  460. * @param string $name the name of the attribute
  461. * @return bool whether the model has an attribute with the specified name.
  462. */
  463. public function hasAttribute($name)
  464. {
  465. return isset($this->_attributes[$name]) || in_array($name, $this->attributes(), true);
  466. }
  467. /**
  468. * Returns the named attribute value.
  469. * If this record is the result of a query and the attribute is not loaded,
  470. * `null` will be returned.
  471. * @param string $name the attribute name
  472. * @return mixed the attribute value. `null` if the attribute is not set or does not exist.
  473. * @see hasAttribute()
  474. */
  475. public function getAttribute($name)
  476. {
  477. return isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
  478. }
  479. /**
  480. * Sets the named attribute value.
  481. * @param string $name the attribute name
  482. * @param mixed $value the attribute value.
  483. * @throws InvalidArgumentException if the named attribute does not exist.
  484. * @see hasAttribute()
  485. */
  486. public function setAttribute($name, $value)
  487. {
  488. if ($this->hasAttribute($name)) {
  489. if (
  490. !empty($this->_relationsDependencies[$name])
  491. && (!array_key_exists($name, $this->_attributes) || $this->_attributes[$name] !== $value)
  492. ) {
  493. $this->resetDependentRelations($name);
  494. }
  495. $this->_attributes[$name] = $value;
  496. } else {
  497. throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
  498. }
  499. }
  500. /**
  501. * Returns the old attribute values.
  502. * @return array the old attribute values (name-value pairs)
  503. */
  504. public function getOldAttributes()
  505. {
  506. return $this->_oldAttributes === null ? [] : $this->_oldAttributes;
  507. }
  508. /**
  509. * Sets the old attribute values.
  510. * All existing old attribute values will be discarded.
  511. * @param array|null $values old attribute values to be set.
  512. * If set to `null` this record is considered to be [[isNewRecord|new]].
  513. */
  514. public function setOldAttributes($values)
  515. {
  516. $this->_oldAttributes = $values;
  517. }
  518. /**
  519. * Returns the old value of the named attribute.
  520. * If this record is the result of a query and the attribute is not loaded,
  521. * `null` will be returned.
  522. * @param string $name the attribute name
  523. * @return mixed the old attribute value. `null` if the attribute is not loaded before
  524. * or does not exist.
  525. * @see hasAttribute()
  526. */
  527. public function getOldAttribute($name)
  528. {
  529. return isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
  530. }
  531. /**
  532. * Sets the old value of the named attribute.
  533. * @param string $name the attribute name
  534. * @param mixed $value the old attribute value.
  535. * @throws InvalidArgumentException if the named attribute does not exist.
  536. * @see hasAttribute()
  537. */
  538. public function setOldAttribute($name, $value)
  539. {
  540. if ($this->canSetOldAttribute($name)) {
  541. $this->_oldAttributes[$name] = $value;
  542. } else {
  543. throw new InvalidArgumentException(get_class($this) . ' has no attribute named "' . $name . '".');
  544. }
  545. }
  546. /**
  547. * Returns if the old named attribute can be set.
  548. * @param string $name the attribute name
  549. * @return bool whether the old attribute can be set
  550. * @see setOldAttribute()
  551. */
  552. public function canSetOldAttribute($name)
  553. {
  554. return (isset($this->_oldAttributes[$name]) || $this->hasAttribute($name));
  555. }
  556. /**
  557. * Marks an attribute dirty.
  558. * This method may be called to force updating a record when calling [[update()]],
  559. * even if there is no change being made to the record.
  560. * @param string $name the attribute name
  561. */
  562. public function markAttributeDirty($name)
  563. {
  564. unset($this->_oldAttributes[$name]);
  565. }
  566. /**
  567. * Returns a value indicating whether the named attribute has been changed.
  568. * @param string $name the name of the attribute.
  569. * @param bool $identical whether the comparison of new and old value is made for
  570. * identical values using `===`, defaults to `true`. Otherwise `==` is used for comparison.
  571. * This parameter is available since version 2.0.4.
  572. * @return bool whether the attribute has been changed
  573. */
  574. public function isAttributeChanged($name, $identical = true)
  575. {
  576. if (isset($this->_attributes[$name], $this->_oldAttributes[$name])) {
  577. if ($identical) {
  578. return $this->_attributes[$name] !== $this->_oldAttributes[$name];
  579. }
  580. return $this->_attributes[$name] != $this->_oldAttributes[$name];
  581. }
  582. return isset($this->_attributes[$name]) || isset($this->_oldAttributes[$name]);
  583. }
  584. /**
  585. * Returns the attribute values that have been modified since they are loaded or saved most recently.
  586. *
  587. * The comparison of new and old values is made for identical values using `===`.
  588. *
  589. * @param string[]|null $names the names of the attributes whose values may be returned if they are
  590. * changed recently. If null, [[attributes()]] will be used.
  591. * @return array the changed attribute values (name-value pairs)
  592. */
  593. public function getDirtyAttributes($names = null)
  594. {
  595. if ($names === null) {
  596. $names = $this->attributes();
  597. }
  598. $names = array_flip($names);
  599. $attributes = [];
  600. if ($this->_oldAttributes === null) {
  601. foreach ($this->_attributes as $name => $value) {
  602. if (isset($names[$name])) {
  603. $attributes[$name] = $value;
  604. }
  605. }
  606. } else {
  607. foreach ($this->_attributes as $name => $value) {
  608. if (isset($names[$name]) && (!array_key_exists($name, $this->_oldAttributes) || $this->isValueDifferent($value, $this->_oldAttributes[$name]))) {
  609. $attributes[$name] = $value;
  610. }
  611. }
  612. }
  613. return $attributes;
  614. }
  615. /**
  616. * Saves the current record.
  617. *
  618. * This method will call [[insert()]] when [[isNewRecord]] is `true`, or [[update()]]
  619. * when [[isNewRecord]] is `false`.
  620. *
  621. * For example, to save a customer record:
  622. *
  623. * ```php
  624. * $customer = new Customer; // or $customer = Customer::findOne($id);
  625. * $customer->name = $name;
  626. * $customer->email = $email;
  627. * $customer->save();
  628. * ```
  629. *
  630. * @param bool $runValidation whether to perform validation (calling [[validate()]])
  631. * before saving the record. Defaults to `true`. If the validation fails, the record
  632. * will not be saved to the database and this method will return `false`.
  633. * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
  634. * meaning all attributes that are loaded from DB will be saved.
  635. * @return bool whether the saving succeeded (i.e. no validation errors occurred).
  636. */
  637. public function save($runValidation = true, $attributeNames = null)
  638. {
  639. if ($this->getIsNewRecord()) {
  640. return $this->insert($runValidation, $attributeNames);
  641. }
  642. return $this->update($runValidation, $attributeNames) !== false;
  643. }
  644. /**
  645. * Saves the changes to this active record into the associated database table.
  646. *
  647. * This method performs the following steps in order:
  648. *
  649. * 1. call [[beforeValidate()]] when `$runValidation` is `true`. If [[beforeValidate()]]
  650. * returns `false`, the rest of the steps will be skipped;
  651. * 2. call [[afterValidate()]] when `$runValidation` is `true`. If validation
  652. * failed, the rest of the steps will be skipped;
  653. * 3. call [[beforeSave()]]. If [[beforeSave()]] returns `false`,
  654. * the rest of the steps will be skipped;
  655. * 4. save the record into database. If this fails, it will skip the rest of the steps;
  656. * 5. call [[afterSave()]];
  657. *
  658. * In the above step 1, 2, 3 and 5, events [[EVENT_BEFORE_VALIDATE]],
  659. * [[EVENT_AFTER_VALIDATE]], [[EVENT_BEFORE_UPDATE]], and [[EVENT_AFTER_UPDATE]]
  660. * will be raised by the corresponding methods.
  661. *
  662. * Only the [[dirtyAttributes|changed attribute values]] will be saved into database.
  663. *
  664. * For example, to update a customer record:
  665. *
  666. * ```php
  667. * $customer = Customer::findOne($id);
  668. * $customer->name = $name;
  669. * $customer->email = $email;
  670. * $customer->update();
  671. * ```
  672. *
  673. * Note that it is possible the update does not affect any row in the table.
  674. * In this case, this method will return 0. For this reason, you should use the following
  675. * code to check if update() is successful or not:
  676. *
  677. * ```php
  678. * if ($customer->update() !== false) {
  679. * // update successful
  680. * } else {
  681. * // update failed
  682. * }
  683. * ```
  684. *
  685. * @param bool $runValidation whether to perform validation (calling [[validate()]])
  686. * before saving the record. Defaults to `true`. If the validation fails, the record
  687. * will not be saved to the database and this method will return `false`.
  688. * @param array|null $attributeNames list of attribute names that need to be saved. Defaults to null,
  689. * meaning all attributes that are loaded from DB will be saved.
  690. * @return int|false the number of rows affected, or `false` if validation fails
  691. * or [[beforeSave()]] stops the updating process.
  692. * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
  693. * being updated is outdated.
  694. * @throws Exception in case update failed.
  695. */
  696. public function update($runValidation = true, $attributeNames = null)
  697. {
  698. if ($runValidation && !$this->validate($attributeNames)) {
  699. return false;
  700. }
  701. return $this->updateInternal($attributeNames);
  702. }
  703. /**
  704. * Updates the specified attributes.
  705. *
  706. * This method is a shortcut to [[update()]] when data validation is not needed
  707. * and only a small set attributes need to be updated.
  708. *
  709. * You may specify the attributes to be updated as name list or name-value pairs.
  710. * If the latter, the corresponding attribute values will be modified accordingly.
  711. * The method will then save the specified attributes into database.
  712. *
  713. * Note that this method will **not** perform data validation and will **not** trigger events.
  714. *
  715. * @param array $attributes the attributes (names or name-value pairs) to be updated
  716. * @return int the number of rows affected.
  717. */
  718. public function updateAttributes($attributes)
  719. {
  720. $attrs = [];
  721. foreach ($attributes as $name => $value) {
  722. if (is_int($name)) {
  723. $attrs[] = $value;
  724. } else {
  725. $this->$name = $value;
  726. $attrs[] = $name;
  727. }
  728. }
  729. $values = $this->getDirtyAttributes($attrs);
  730. if (empty($values) || $this->getIsNewRecord()) {
  731. return 0;
  732. }
  733. $rows = static::updateAll($values, $this->getOldPrimaryKey(true));
  734. foreach ($values as $name => $value) {
  735. $this->_oldAttributes[$name] = $this->_attributes[$name];
  736. }
  737. return $rows;
  738. }
  739. /**
  740. * @see update()
  741. * @param array|null $attributes attributes to update
  742. * @return int|false the number of rows affected, or false if [[beforeSave()]] stops the updating process.
  743. * @throws StaleObjectException
  744. */
  745. protected function updateInternal($attributes = null)
  746. {
  747. if (!$this->beforeSave(false)) {
  748. return false;
  749. }
  750. $values = $this->getDirtyAttributes($attributes);
  751. if (empty($values)) {
  752. $this->afterSave(false, $values);
  753. return 0;
  754. }
  755. $condition = $this->getOldPrimaryKey(true);
  756. $lock = $this->optimisticLock();
  757. if ($lock !== null) {
  758. $values[$lock] = $this->$lock + 1;
  759. $condition[$lock] = $this->$lock;
  760. }
  761. // We do not check the return value of updateAll() because it's possible
  762. // that the UPDATE statement doesn't change anything and thus returns 0.
  763. $rows = static::updateAll($values, $condition);
  764. if ($lock !== null && !$rows) {
  765. throw new StaleObjectException('The object being updated is outdated.');
  766. }
  767. if (isset($values[$lock])) {
  768. $this->$lock = $values[$lock];
  769. }
  770. $changedAttributes = [];
  771. foreach ($values as $name => $value) {
  772. $changedAttributes[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
  773. $this->_oldAttributes[$name] = $value;
  774. }
  775. $this->afterSave(false, $changedAttributes);
  776. return $rows;
  777. }
  778. /**
  779. * Updates one or several counter columns for the current AR object.
  780. * Note that this method differs from [[updateAllCounters()]] in that it only
  781. * saves counters for the current AR object.
  782. *
  783. * An example usage is as follows:
  784. *
  785. * ```php
  786. * $post = Post::findOne($id);
  787. * $post->updateCounters(['view_count' => 1]);
  788. * ```
  789. *
  790. * @param array $counters the counters to be updated (attribute name => increment value)
  791. * Use negative values if you want to decrement the counters.
  792. * @return bool whether the saving is successful
  793. * @see updateAllCounters()
  794. */
  795. public function updateCounters($counters)
  796. {
  797. if (static::updateAllCounters($counters, $this->getOldPrimaryKey(true)) > 0) {
  798. foreach ($counters as $name => $value) {
  799. if (!isset($this->_attributes[$name])) {
  800. $this->_attributes[$name] = $value;
  801. } else {
  802. $this->_attributes[$name] += $value;
  803. }
  804. $this->_oldAttributes[$name] = $this->_attributes[$name];
  805. }
  806. return true;
  807. }
  808. return false;
  809. }
  810. /**
  811. * Deletes the table row corresponding to this active record.
  812. *
  813. * This method performs the following steps in order:
  814. *
  815. * 1. call [[beforeDelete()]]. If the method returns `false`, it will skip the
  816. * rest of the steps;
  817. * 2. delete the record from the database;
  818. * 3. call [[afterDelete()]].
  819. *
  820. * In the above step 1 and 3, events named [[EVENT_BEFORE_DELETE]] and [[EVENT_AFTER_DELETE]]
  821. * will be raised by the corresponding methods.
  822. *
  823. * @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason.
  824. * Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful.
  825. * @throws StaleObjectException if [[optimisticLock|optimistic locking]] is enabled and the data
  826. * being deleted is outdated.
  827. * @throws Exception in case delete failed.
  828. */
  829. public function delete()
  830. {
  831. $result = false;
  832. if ($this->beforeDelete()) {
  833. // we do not check the return value of deleteAll() because it's possible
  834. // the record is already deleted in the database and thus the method will return 0
  835. $condition = $this->getOldPrimaryKey(true);
  836. $lock = $this->optimisticLock();
  837. if ($lock !== null) {
  838. $condition[$lock] = $this->$lock;
  839. }
  840. $result = static::deleteAll($condition);
  841. if ($lock !== null && !$result) {
  842. throw new StaleObjectException('The object being deleted is outdated.');
  843. }
  844. $this->_oldAttributes = null;
  845. $this->afterDelete();
  846. }
  847. return $result;
  848. }
  849. /**
  850. * Returns a value indicating whether the current record is new.
  851. * @return bool whether the record is new and should be inserted when calling [[save()]].
  852. */
  853. public function getIsNewRecord()
  854. {
  855. return $this->_oldAttributes === null;
  856. }
  857. /**
  858. * Sets the value indicating whether the record is new.
  859. * @param bool $value whether the record is new and should be inserted when calling [[save()]].
  860. * @see getIsNewRecord()
  861. */
  862. public function setIsNewRecord($value)
  863. {
  864. $this->_oldAttributes = $value ? null : $this->_attributes;
  865. }
  866. /**
  867. * Initializes the object.
  868. * This method is called at the end of the constructor.
  869. * The default implementation will trigger an [[EVENT_INIT]] event.
  870. */
  871. public function init()
  872. {
  873. parent::init();
  874. $this->trigger(self::EVENT_INIT);
  875. }
  876. /**
  877. * This method is called when the AR object is created and populated with the query result.
  878. * The default implementation will trigger an [[EVENT_AFTER_FIND]] event.
  879. * When overriding this method, make sure you call the parent implementation to ensure the
  880. * event is triggered.
  881. */
  882. public function afterFind()
  883. {
  884. $this->trigger(self::EVENT_AFTER_FIND);
  885. }
  886. /**
  887. * This method is called at the beginning of inserting or updating a record.
  888. *
  889. * The default implementation will trigger an [[EVENT_BEFORE_INSERT]] event when `$insert` is `true`,
  890. * or an [[EVENT_BEFORE_UPDATE]] event if `$insert` is `false`.
  891. * When overriding this method, make sure you call the parent implementation like the following:
  892. *
  893. * ```php
  894. * public function beforeSave($insert)
  895. * {
  896. * if (!parent::beforeSave($insert)) {
  897. * return false;
  898. * }
  899. *
  900. * // ...custom code here...
  901. * return true;
  902. * }
  903. * ```
  904. *
  905. * @param bool $insert whether this method called while inserting a record.
  906. * If `false`, it means the method is called while updating a record.
  907. * @return bool whether the insertion or updating should continue.
  908. * If `false`, the insertion or updating will be cancelled.
  909. */
  910. public function beforeSave($insert)
  911. {
  912. $event = new ModelEvent();
  913. $this->trigger($insert ? self::EVENT_BEFORE_INSERT : self::EVENT_BEFORE_UPDATE, $event);
  914. return $event->isValid;
  915. }
  916. /**
  917. * This method is called at the end of inserting or updating a record.
  918. * The default implementation will trigger an [[EVENT_AFTER_INSERT]] event when `$insert` is `true`,
  919. * or an [[EVENT_AFTER_UPDATE]] event if `$insert` is `false`. The event class used is [[AfterSaveEvent]].
  920. * When overriding this method, make sure you call the parent implementation so that
  921. * the event is triggered.
  922. * @param bool $insert whether this method called while inserting a record.
  923. * If `false`, it means the method is called while updating a record.
  924. * @param array $changedAttributes The old values of attributes that had changed and were saved.
  925. * You can use this parameter to take action based on the changes made for example send an email
  926. * when the password had changed or implement audit trail that tracks all the changes.
  927. * `$changedAttributes` gives you the old attribute values while the active record (`$this`) has
  928. * already the new, updated values.
  929. *
  930. * Note that no automatic type conversion performed by default. You may use
  931. * [[\yii\behaviors\AttributeTypecastBehavior]] to facilitate attribute typecasting.
  932. * See https://www.yiiframework.com/doc-2.0/guide-db-active-record.html#attributes-typecasting.
  933. */
  934. public function afterSave($insert, $changedAttributes)
  935. {
  936. $this->trigger($insert ? self::EVENT_AFTER_INSERT : self::EVENT_AFTER_UPDATE, new AfterSaveEvent([
  937. 'changedAttributes' => $changedAttributes,
  938. ]));
  939. }
  940. /**
  941. * This method is invoked before deleting a record.
  942. *
  943. * The default implementation raises the [[EVENT_BEFORE_DELETE]] event.
  944. * When overriding this method, make sure you call the parent implementation like the following:
  945. *
  946. * ```php
  947. * public function beforeDelete()
  948. * {
  949. * if (!parent::beforeDelete()) {
  950. * return false;
  951. * }
  952. *
  953. * // ...custom code here...
  954. * return true;
  955. * }
  956. * ```
  957. *
  958. * @return bool whether the record should be deleted. Defaults to `true`.
  959. */
  960. public function beforeDelete()
  961. {
  962. $event = new ModelEvent();
  963. $this->trigger(self::EVENT_BEFORE_DELETE, $event);
  964. return $event->isValid;
  965. }
  966. /**
  967. * This method is invoked after deleting a record.
  968. * The default implementation raises the [[EVENT_AFTER_DELETE]] event.
  969. * You may override this method to do postprocessing after the record is deleted.
  970. * Make sure you call the parent implementation so that the event is raised properly.
  971. */
  972. public function afterDelete()
  973. {
  974. $this->trigger(self::EVENT_AFTER_DELETE);
  975. }
  976. /**
  977. * Repopulates this active record with the latest data.
  978. *
  979. * If the refresh is successful, an [[EVENT_AFTER_REFRESH]] event will be triggered.
  980. * This event is available since version 2.0.8.
  981. *
  982. * @return bool whether the row still exists in the database. If `true`, the latest data
  983. * will be populated to this active record. Otherwise, this record will remain unchanged.
  984. */
  985. public function refresh()
  986. {
  987. /* @var $record BaseActiveRecord */
  988. $record = static::findOne($this->getPrimaryKey(true));
  989. return $this->refreshInternal($record);
  990. }
  991. /**
  992. * Repopulates this active record with the latest data from a newly fetched instance.
  993. * @param BaseActiveRecord $record the record to take attributes from.
  994. * @return bool whether refresh was successful.
  995. * @see refresh()
  996. * @since 2.0.13
  997. */
  998. protected function refreshInternal($record)
  999. {
  1000. if ($record === null) {
  1001. return false;
  1002. }
  1003. foreach ($this->attributes() as $name) {
  1004. $this->_attributes[$name] = isset($record->_attributes[$name]) ? $record->_attributes[$name] : null;
  1005. }
  1006. $this->_oldAttributes = $record->_oldAttributes;
  1007. $this->_related = [];
  1008. $this->_relationsDependencies = [];
  1009. $this->afterRefresh();
  1010. return true;
  1011. }
  1012. /**
  1013. * This method is called when the AR object is refreshed.
  1014. * The default implementation will trigger an [[EVENT_AFTER_REFRESH]] event.
  1015. * When overriding this method, make sure you call the parent implementation to ensure the
  1016. * event is triggered.
  1017. * @since 2.0.8
  1018. */
  1019. public function afterRefresh()
  1020. {
  1021. $this->trigger(self::EVENT_AFTER_REFRESH);
  1022. }
  1023. /**
  1024. * Returns a value indicating whether the given active record is the same as the current one.
  1025. * The comparison is made by comparing the table names and the primary key values of the two active records.
  1026. * If one of the records [[isNewRecord|is new]] they are also considered not equal.
  1027. * @param ActiveRecordInterface $record record to compare to
  1028. * @return bool whether the two active records refer to the same row in the same database table.
  1029. */
  1030. public function equals($record)
  1031. {
  1032. if ($this->getIsNewRecord() || $record->getIsNewRecord()) {
  1033. return false;
  1034. }
  1035. return get_class($this) === get_class($record) && $this->getPrimaryKey() === $record->getPrimaryKey();
  1036. }
  1037. /**
  1038. * Returns the primary key value(s).
  1039. * @param bool $asArray whether to return the primary key value as an array. If `true`,
  1040. * the return value will be an array with column names as keys and column values as values.
  1041. * Note that for composite primary keys, an array will always be returned regardless of this parameter value.
  1042. * @return mixed the primary key value. An array (column name => column value) is returned if the primary key
  1043. * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
  1044. * the key value is null).
  1045. */
  1046. public function getPrimaryKey($asArray = false)
  1047. {
  1048. $keys = static::primaryKey();
  1049. if (!$asArray && count($keys) === 1) {
  1050. return isset($this->_attributes[$keys[0]]) ? $this->_attributes[$keys[0]] : null;
  1051. }
  1052. $values = [];
  1053. foreach ($keys as $name) {
  1054. $values[$name] = isset($this->_attributes[$name]) ? $this->_attributes[$name] : null;
  1055. }
  1056. return $values;
  1057. }
  1058. /**
  1059. * Returns the old primary key value(s).
  1060. * This refers to the primary key value that is populated into the record
  1061. * after executing a find method (e.g. find(), findOne()).
  1062. * The value remains unchanged even if the primary key attribute is manually assigned with a different value.
  1063. * @param bool $asArray whether to return the primary key value as an array. If `true`,
  1064. * the return value will be an array with column name as key and column value as value.
  1065. * If this is `false` (default), a scalar value will be returned for non-composite primary key.
  1066. * @return mixed the old primary key value. An array (column name => column value) is returned if the primary key
  1067. * is composite or `$asArray` is `true`. A string is returned otherwise (null will be returned if
  1068. * the key value is null).
  1069. * @throws Exception if the AR model does not have a primary key
  1070. */
  1071. public function getOldPrimaryKey($asArray = false)
  1072. {
  1073. $keys = static::primaryKey();
  1074. if (empty($keys)) {
  1075. throw new Exception(get_class($this) . ' does not have a primary key. You should either define a primary key for the corresponding table or override the primaryKey() method.');
  1076. }
  1077. if (!$asArray && count($keys) === 1) {
  1078. return isset($this->_oldAttributes[$keys[0]]) ? $this->_oldAttributes[$keys[0]] : null;
  1079. }
  1080. $values = [];
  1081. foreach ($keys as $name) {
  1082. $values[$name] = isset($this->_oldAttributes[$name]) ? $this->_oldAttributes[$name] : null;
  1083. }
  1084. return $values;
  1085. }
  1086. /**
  1087. * Populates an active record object using a row of data from the database/storage.
  1088. *
  1089. * This is an internal method meant to be called to create active record objects after
  1090. * fetching data from the database. It is mainly used by [[ActiveQuery]] to populate
  1091. * the query results into active records.
  1092. *
  1093. * When calling this method manually you should call [[afterFind()]] on the created
  1094. * record to trigger the [[EVENT_AFTER_FIND|afterFind Event]].
  1095. *
  1096. * @param BaseActiveRecord $record the record to be populated. In most cases this will be an instance
  1097. * created by [[instantiate()]] beforehand.
  1098. * @param array $row attribute values (name => value)
  1099. */
  1100. public static function populateRecord($record, $row)
  1101. {
  1102. $columns = array_flip($record->attributes());
  1103. foreach ($row as $name => $value) {
  1104. if (isset($columns[$name])) {
  1105. $record->_attributes[$name] = $value;
  1106. } elseif ($record->canSetProperty($name)) {
  1107. $record->$name = $value;
  1108. }
  1109. }
  1110. $record->_oldAttributes = $record->_attributes;
  1111. $record->_related = [];
  1112. $record->_relationsDependencies = [];
  1113. }
  1114. /**
  1115. * Creates an active record instance.
  1116. *
  1117. * This method is called together with [[populateRecord()]] by [[ActiveQuery]].
  1118. * It is not meant to be used for creating new records directly.
  1119. *
  1120. * You may override this method if the instance being created
  1121. * depends on the row data to be populated into the record.
  1122. * For example, by creating a record based on the value of a column,
  1123. * you may implement the so-called single-table inheritance mapping.
  1124. * @param array $row row data to be populated into the record.
  1125. * @return static the newly created active record
  1126. */
  1127. public static function instantiate($row)
  1128. {
  1129. return new static();
  1130. }
  1131. /**
  1132. * Returns whether there is an element at the specified offset.
  1133. * This method is required by the interface [[\ArrayAccess]].
  1134. * @param mixed $offset the offset to check on
  1135. * @return bool whether there is an element at the specified offset.
  1136. */
  1137. #[\ReturnTypeWillChange]
  1138. public function offsetExists($offset)
  1139. {
  1140. return $this->__isset($offset);
  1141. }
  1142. /**
  1143. * Returns the relation object with the specified name.
  1144. * A relation is defined by a getter method which returns an [[ActiveQueryInterface]] object.
  1145. * It can be declared in either the Active Record class itself or one of its behaviors.
  1146. * @param string $name the relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive).
  1147. * @param bool $throwException whether to throw exception if the relation does not exist.
  1148. * @return ActiveQueryInterface|ActiveQuery|null the relational query object. If the relation does not exist
  1149. * and `$throwException` is `false`, `null` will be returned.
  1150. * @throws InvalidArgumentException if the named relation does not exist.
  1151. */
  1152. public function getRelation($name, $throwException = true)
  1153. {
  1154. $getter = 'get' . $name;
  1155. try {
  1156. // the relation could be defined in a behavior
  1157. $relation = $this->$getter();
  1158. } catch (UnknownMethodException $e) {
  1159. if ($throwException) {
  1160. throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".', 0, $e);
  1161. }
  1162. return null;
  1163. }
  1164. if (!$relation instanceof ActiveQueryInterface) {
  1165. if ($throwException) {
  1166. throw new InvalidArgumentException(get_class($this) . ' has no relation named "' . $name . '".');
  1167. }
  1168. return null;
  1169. }
  1170. if (method_exists($this, $getter)) {
  1171. // relation name is case sensitive, trying to validate it when the relation is defined within this class
  1172. $method = new \ReflectionMethod($this, $getter);
  1173. $realName = lcfirst(substr($method->getName(), 3));
  1174. if ($realName !== $name) {
  1175. if ($throwException) {
  1176. throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($this) . " has a relation named \"$realName\" instead of \"$name\".");
  1177. }
  1178. return null;
  1179. }
  1180. }
  1181. return $relation;
  1182. }
  1183. /**
  1184. * Establishes the relationship between two models.
  1185. *
  1186. * The relationship is established by setting the foreign key value(s) in one model
  1187. * to be the corresponding primary key value(s) in the other model.
  1188. * The model with the foreign key will be saved into database **without** performing validation
  1189. * and **without** events/behaviors.
  1190. *
  1191. * If the relationship involves a junction table, a new row will be inserted into the
  1192. * junction table which contains the primary key values from both models.
  1193. *
  1194. * Note that this method requires that the primary key value is not null.
  1195. *
  1196. * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
  1197. * @param ActiveRecordInterface $model the model to be linked with the current one.
  1198. * @param array $extraColumns additional column values to be saved into the junction table.
  1199. * This parameter is only meaningful for a relationship involving a junction table
  1200. * (i.e., a relation set with [[ActiveRelationTrait::via()]] or [[ActiveQuery::viaTable()]].)
  1201. * @throws InvalidCallException if the method is unable to link two models.
  1202. */
  1203. public function link($name, $model, $extraColumns = [])
  1204. {
  1205. /* @var $relation ActiveQueryInterface|ActiveQuery */
  1206. $relation = $this->getRelation($name);
  1207. if ($relation->via !== null) {
  1208. if ($this->getIsNewRecord() || $model->getIsNewRecord()) {
  1209. throw new InvalidCallException('Unable to link models: the models being linked cannot be newly created.');
  1210. }
  1211. if (is_array($relation->via)) {
  1212. /* @var $viaRelation ActiveQuery */
  1213. list($viaName, $viaRelation) = $relation->via;
  1214. $viaClass = $viaRelation->modelClass;
  1215. // unset $viaName so that it can be reloaded to reflect the change
  1216. unset($this->_related[$viaName]);
  1217. } else {
  1218. $viaRelation = $relation->via;
  1219. $viaTable = reset($relation->via->from);
  1220. }
  1221. $columns = [];
  1222. foreach ($viaRelation->link as $a => $b) {
  1223. $columns[$a] = $this->$b;
  1224. }
  1225. foreach ($relation->link as $a => $b) {
  1226. $columns[$b] = $model->$a;
  1227. }
  1228. foreach ($extraColumns as $k => $v) {
  1229. $columns[$k] = $v;
  1230. }
  1231. if (is_array($relation->via)) {
  1232. /* @var $viaClass ActiveRecordInterface */
  1233. /* @var $record ActiveRecordInterface */
  1234. $record = Yii::createObject($viaClass);
  1235. foreach ($columns as $column => $value) {
  1236. $record->$column = $value;
  1237. }
  1238. $record->insert(false);
  1239. } else {
  1240. /* @var $viaTable string */
  1241. static::getDb()->createCommand()->insert($viaTable, $columns)->execute();
  1242. }
  1243. } else {
  1244. $p1 = $model->isPrimaryKey(array_keys($relation->link));
  1245. $p2 = static::isPrimaryKey(array_values($relation->link));
  1246. if ($p1 && $p2) {
  1247. if ($this->getIsNewRecord()) {
  1248. if ($model->getIsNewRecord()) {
  1249. throw new InvalidCallException('Unable to link models: at most one model can be newly created.');
  1250. }
  1251. $this->bindModels(array_flip($relation->link), $this, $model);
  1252. } else {
  1253. $this->bindModels($relation->link, $model, $this);
  1254. }
  1255. } elseif ($p1) {
  1256. $this->bindModels(array_flip($relation->link), $this, $model);
  1257. } elseif ($p2) {
  1258. $this->bindModels($relation->link, $model, $this);
  1259. } else {
  1260. throw new InvalidCallException('Unable to link models: the link defining the relation does not involve any primary key.');
  1261. }
  1262. }
  1263. // update lazily loaded related objects
  1264. if (!$relation->multiple) {
  1265. $this->_related[$name] = $model;
  1266. } elseif (isset($this->_related[$name])) {
  1267. if ($relation->indexBy !== null) {
  1268. if ($relation->indexBy instanceof \Closure) {
  1269. $index = call_user_func($relation->indexBy, $model);
  1270. } else {
  1271. $index = $model->{$relation->indexBy};
  1272. }
  1273. $this->_related[$name][$index] = $model;
  1274. } else {
  1275. $this->_related[$name][] = $model;
  1276. }
  1277. }
  1278. }
  1279. /**
  1280. * Destroys the relationship between two models.
  1281. *
  1282. * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
  1283. * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
  1284. *
  1285. * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
  1286. * @param ActiveRecordInterface $model the model to be unlinked from the current one.
  1287. * You have to make sure that the model is really related with the current model as this method
  1288. * does not check this.
  1289. * @param bool $delete whether to delete the model that contains the foreign key.
  1290. * If `false`, the model's foreign key will be set `null` and saved.
  1291. * If `true`, the model containing the foreign key will be deleted.
  1292. * @throws InvalidCallException if the models cannot be unlinked
  1293. * @throws Exception
  1294. * @throws StaleObjectException
  1295. */
  1296. public function unlink($name, $model, $delete = false)
  1297. {
  1298. /* @var $relation ActiveQueryInterface|ActiveQuery */
  1299. $relation = $this->getRelation($name);
  1300. if ($relation->via !== null) {
  1301. if (is_array($relation->via)) {
  1302. /* @var $viaRelation ActiveQuery */
  1303. list($viaName, $viaRelation) = $relation->via;
  1304. $viaClass = $viaRelation->modelClass;
  1305. unset($this->_related[$viaName]);
  1306. } else {
  1307. $viaRelation = $relation->via;
  1308. $viaTable = reset($relation->via->from);
  1309. }
  1310. $columns = [];
  1311. foreach ($viaRelation->link as $a => $b) {
  1312. $columns[$a] = $this->$b;
  1313. }
  1314. foreach ($relation->link as $a => $b) {
  1315. $columns[$b] = $model->$a;
  1316. }
  1317. $nulls = [];
  1318. foreach (array_keys($columns) as $a) {
  1319. $nulls[$a] = null;
  1320. }
  1321. if (property_exists($viaRelation, 'on') && $viaRelation->on !== null) {
  1322. $columns = ['and', $columns, $viaRelation->on];
  1323. }
  1324. if (is_array($relation->via)) {
  1325. /* @var $viaClass ActiveRecordInterface */
  1326. if ($delete) {
  1327. $viaClass::deleteAll($columns);
  1328. } else {
  1329. $viaClass::updateAll($nulls, $columns);
  1330. }
  1331. } else {
  1332. /* @var $viaTable string */
  1333. /* @var $command Command */
  1334. $command = static::getDb()->createCommand();
  1335. if ($delete) {
  1336. $command->delete($viaTable, $columns)->execute();
  1337. } else {
  1338. $command->update($viaTable, $nulls, $columns)->execute();
  1339. }
  1340. }
  1341. } else {
  1342. $p1 = $model->isPrimaryKey(array_keys($relation->link));
  1343. $p2 = static::isPrimaryKey(array_values($relation->link));
  1344. if ($p2) {
  1345. if ($delete) {
  1346. $model->delete();
  1347. } else {
  1348. foreach ($relation->link as $a => $b) {
  1349. $model->$a = null;
  1350. }
  1351. $model->save(false);
  1352. }
  1353. } elseif ($p1) {
  1354. foreach ($relation->link as $a => $b) {
  1355. if (is_array($this->$b)) { // relation via array valued attribute
  1356. if (($key = array_search($model->$a, $this->$b, false)) !== false) {
  1357. $values = $this->$b;
  1358. unset($values[$key]);
  1359. $this->$b = array_values($values);
  1360. }
  1361. } else {
  1362. $this->$b = null;
  1363. }
  1364. }
  1365. $delete ? $this->delete() : $this->save(false);
  1366. } else {
  1367. throw new InvalidCallException('Unable to unlink models: the link does not involve any primary key.');
  1368. }
  1369. }
  1370. if (!$relation->multiple) {
  1371. unset($this->_related[$name]);
  1372. } elseif (isset($this->_related[$name])) {
  1373. /* @var $b ActiveRecordInterface */
  1374. foreach ($this->_related[$name] as $a => $b) {
  1375. if ($model->getPrimaryKey() === $b->getPrimaryKey()) {
  1376. unset($this->_related[$name][$a]);
  1377. }
  1378. }
  1379. }
  1380. }
  1381. /**
  1382. * Destroys the relationship in current model.
  1383. *
  1384. * The model with the foreign key of the relationship will be deleted if `$delete` is `true`.
  1385. * Otherwise, the foreign key will be set `null` and the model will be saved without validation.
  1386. *
  1387. * Note that to destroy the relationship without removing records make sure your keys can be set to null
  1388. *
  1389. * @param string $name the case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method.
  1390. * @param bool $delete whether to delete the model that contains the foreign key.
  1391. *
  1392. * Note that the deletion will be performed using [[deleteAll()]], which will not trigger any events on the related models.
  1393. * If you need [[EVENT_BEFORE_DELETE]] or [[EVENT_AFTER_DELETE]] to be triggered, you need to [[find()|find]] the models first
  1394. * and then call [[delete()]] on each of them.
  1395. */
  1396. public function unlinkAll($name, $delete = false)
  1397. {
  1398. /* @var $relation ActiveQueryInterface|ActiveQuery */
  1399. $relation = $this->getRelation($name);
  1400. if ($relation->via !== null) {
  1401. if (is_array($relation->via)) {
  1402. /* @var $viaRelation ActiveQuery */
  1403. list($viaName, $viaRelation) = $relation->via;
  1404. $viaClass = $viaRelation->modelClass;
  1405. unset($this->_related[$viaName]);
  1406. } else {
  1407. $viaRelation = $relation->via;
  1408. $viaTable = reset($relation->via->from);
  1409. }
  1410. $condition = [];
  1411. $nulls = [];
  1412. foreach ($viaRelation->link as $a => $b) {
  1413. $nulls[$a] = null;
  1414. $condition[$a] = $this->$b;
  1415. }
  1416. if (!empty($viaRelation->where)) {
  1417. $condition = ['and', $condition, $viaRelation->where];
  1418. }
  1419. if (property_exists($viaRelation, 'on') && !empty($viaRelation->on)) {
  1420. $condition = ['and', $condition, $viaRelation->on];
  1421. }
  1422. if (is_array($relation->via)) {
  1423. /* @var $viaClass ActiveRecordInterface */
  1424. if ($delete) {
  1425. $viaClass::deleteAll($condition);
  1426. } else {
  1427. $viaClass::updateAll($nulls, $condition);
  1428. }
  1429. } else {
  1430. /* @var $viaTable string */
  1431. /* @var $command Command */
  1432. $command = static::getDb()->createCommand();
  1433. if ($delete) {
  1434. $command->delete($viaTable, $condition)->execute();
  1435. } else {
  1436. $command->update($viaTable, $nulls, $condition)->execute();
  1437. }
  1438. }
  1439. } else {
  1440. /* @var $relatedModel ActiveRecordInterface */
  1441. $relatedModel = $relation->modelClass;
  1442. if (!$delete && count($relation->link) === 1 && is_array($this->{$b = reset($relation->link)})) {
  1443. // relation via array valued attribute
  1444. $this->$b = [];
  1445. $this->save(false);
  1446. } else {
  1447. $nulls = [];
  1448. $condition = [];
  1449. foreach ($relation->link as $a => $b) {
  1450. $nulls[$a] = null;
  1451. $condition[$a] = $this->$b;
  1452. }
  1453. if (!empty($relation->where)) {
  1454. $condition = ['and', $condition, $relation->where];
  1455. }
  1456. if (property_exists($relation, 'on') && !empty($relation->on)) {
  1457. $condition = ['and', $condition, $relation->on];
  1458. }
  1459. if ($delete) {
  1460. $relatedModel::deleteAll($condition);
  1461. } else {
  1462. $relatedModel::updateAll($nulls, $condition);
  1463. }
  1464. }
  1465. }
  1466. unset($this->_related[$name]);
  1467. }
  1468. /**
  1469. * @param array $link
  1470. * @param ActiveRecordInterface $foreignModel
  1471. * @param ActiveRecordInterface $primaryModel
  1472. * @throws InvalidCallException
  1473. */
  1474. private function bindModels($link, $foreignModel, $primaryModel)
  1475. {
  1476. foreach ($link as $fk => $pk) {
  1477. $value = $primaryModel->$pk;
  1478. if ($value === null) {
  1479. throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.');
  1480. }
  1481. if (is_array($foreignModel->$fk)) { // relation via array valued attribute
  1482. $foreignModel->{$fk}[] = $value;
  1483. } else {
  1484. $foreignModel->{$fk} = $value;
  1485. }
  1486. }
  1487. $foreignModel->save(false);
  1488. }
  1489. /**
  1490. * Returns a value indicating whether the given set of attributes represents the primary key for this model.
  1491. * @param array $keys the set of attributes to check
  1492. * @return bool whether the given set of attributes represents the primary key for this model
  1493. */
  1494. public static function isPrimaryKey($keys)
  1495. {
  1496. $pks = static::primaryKey();
  1497. if (count($keys) === count($pks)) {
  1498. return count(array_intersect($keys, $pks)) === count($pks);
  1499. }
  1500. return false;
  1501. }
  1502. /**
  1503. * Returns the text label for the specified attribute.
  1504. * The attribute may be specified in a dot format to retrieve the label from related model or allow this model to override the label defined in related model.
  1505. * For example, if the attribute is specified as 'relatedModel1.relatedModel2.attr' the function will return the first label definition it can find
  1506. * in the following order:
  1507. * - the label for 'relatedModel1.relatedModel2.attr' defined in [[attributeLabels()]] of this model;
  1508. * - the label for 'relatedModel2.attr' defined in related model represented by relation 'relatedModel1' of this model;
  1509. * - the label for 'attr' defined in related model represented by relation 'relatedModel2' of relation 'relatedModel1'.
  1510. * If no label definition was found then the value of $this->generateAttributeLabel('relatedModel1.relatedModel2.attr') will be returned.
  1511. * @param string $attribute the attribute name
  1512. * @return string the attribute label
  1513. * @see attributeLabels()
  1514. * @see generateAttributeLabel()
  1515. */
  1516. public function getAttributeLabel($attribute)
  1517. {
  1518. $model = $this;
  1519. $modelAttribute = $attribute;
  1520. for (;;) {
  1521. $labels = $model->attributeLabels();
  1522. if (isset($labels[$modelAttribute])) {
  1523. return $labels[$modelAttribute];
  1524. }
  1525. $parts = explode('.', $modelAttribute, 2);
  1526. if (count($parts) < 2) {
  1527. break;
  1528. }
  1529. list ($relationName, $modelAttribute) = $parts;
  1530. if ($model->isRelationPopulated($relationName) && $model->$relationName instanceof self) {
  1531. $model = $model->$relationName;
  1532. } else {
  1533. try {
  1534. $relation = $model->getRelation($relationName);
  1535. } catch (InvalidArgumentException $e) {
  1536. break;
  1537. }
  1538. /* @var $modelClass ActiveRecordInterface */
  1539. $modelClass = $relation->modelClass;
  1540. $model = $modelClass::instance();
  1541. }
  1542. }
  1543. return $this->generateAttributeLabel($attribute);
  1544. }
  1545. /**
  1546. * Returns the text hint for the specified attribute.
  1547. * If the attribute looks like `relatedModel.attribute`, then the attribute will be received from the related model.
  1548. * @param string $attribute the attribute name
  1549. * @return string the attribute hint
  1550. * @see attributeHints()
  1551. * @since 2.0.4
  1552. */
  1553. public function getAttributeHint($attribute)
  1554. {
  1555. $hints = $this->attributeHints();
  1556. if (isset($hints[$attribute])) {
  1557. return $hints[$attribute];
  1558. } elseif (strpos($attribute, '.')) {
  1559. $attributeParts = explode('.', $attribute);
  1560. $neededAttribute = array_pop($attributeParts);
  1561. $relatedModel = $this;
  1562. foreach ($attributeParts as $relationName) {
  1563. if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof self) {
  1564. $relatedModel = $relatedModel->$relationName;
  1565. } else {
  1566. try {
  1567. $relation = $relatedModel->getRelation($relationName);
  1568. } catch (InvalidParamException $e) {
  1569. return '';
  1570. }
  1571. /* @var $modelClass ActiveRecordInterface */
  1572. $modelClass = $relation->modelClass;
  1573. $relatedModel = $modelClass::instance();
  1574. }
  1575. }
  1576. $hints = $relatedModel->attributeHints();
  1577. if (isset($hints[$neededAttribute])) {
  1578. return $hints[$neededAttribute];
  1579. }
  1580. }
  1581. return '';
  1582. }
  1583. /**
  1584. * {@inheritdoc}
  1585. *
  1586. * The default implementation returns the names of the columns whose values have been populated into this record.
  1587. */
  1588. public function fields()
  1589. {
  1590. $fields = array_keys($this->_attributes);
  1591. return array_combine($fields, $fields);
  1592. }
  1593. /**
  1594. * {@inheritdoc}
  1595. *
  1596. * The default implementation returns the names of the relations that have been populated into this record.
  1597. */
  1598. public function extraFields()
  1599. {
  1600. $fields = array_keys($this->getRelatedRecords());
  1601. return array_combine($fields, $fields);
  1602. }
  1603. /**
  1604. * Sets the element value at the specified offset to null.
  1605. * This method is required by the SPL interface [[\ArrayAccess]].
  1606. * It is implicitly called when you use something like `unset($model[$offset])`.
  1607. * @param mixed $offset the offset to unset element
  1608. */
  1609. public function offsetUnset($offset)
  1610. {
  1611. if (property_exists($this, $offset)) {
  1612. $this->$offset = null;
  1613. } else {
  1614. unset($this->$offset);
  1615. }
  1616. }
  1617. /**
  1618. * Resets dependent related models checking if their links contain specific attribute.
  1619. * @param string $attribute The changed attribute name.
  1620. */
  1621. private function resetDependentRelations($attribute)
  1622. {
  1623. foreach ($this->_relationsDependencies[$attribute] as $relation) {
  1624. unset($this->_related[$relation]);
  1625. }
  1626. unset($this->_relationsDependencies[$attribute]);
  1627. }
  1628. /**
  1629. * Sets relation dependencies for a property
  1630. * @param string $name property name
  1631. * @param ActiveQueryInterface $relation relation instance
  1632. * @param string|null $viaRelationName intermediate relation
  1633. */
  1634. private function setRelationDependencies($name, $relation, $viaRelationName = null)
  1635. {
  1636. if (empty($relation->via) && $relation->link) {
  1637. foreach ($relation->link as $attribute) {
  1638. $this->_relationsDependencies[$attribute][$name] = $name;
  1639. if ($viaRelationName !== null) {
  1640. $this->_relationsDependencies[$attribute][] = $viaRelationName;
  1641. }
  1642. }
  1643. } elseif ($relation->via instanceof ActiveQueryInterface) {
  1644. $this->setRelationDependencies($name, $relation->via);
  1645. } elseif (is_array($relation->via)) {
  1646. list($viaRelationName, $viaQuery) = $relation->via;
  1647. $this->setRelationDependencies($name, $viaQuery, $viaRelationName);
  1648. }
  1649. }
  1650. /**
  1651. * @param mixed $newValue
  1652. * @param mixed $oldValue
  1653. * @return bool
  1654. * @since 2.0.48
  1655. */
  1656. private function isValueDifferent($newValue, $oldValue)
  1657. {
  1658. if (is_array($newValue) && is_array($oldValue) && ArrayHelper::isAssociative($oldValue)) {
  1659. $newValue = ArrayHelper::recursiveSort($newValue);
  1660. $oldValue = ArrayHelper::recursiveSort($oldValue);
  1661. }
  1662. return $newValue !== $oldValue;
  1663. }
  1664. }