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