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