|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\ActiveRecord; |
|
6
|
|
|
|
|
7
|
|
|
use Throwable; |
|
8
|
|
|
use Yiisoft\Db\Exception\Exception; |
|
9
|
|
|
use Yiisoft\Db\Exception\InvalidArgumentException; |
|
10
|
|
|
use Yiisoft\Db\Exception\InvalidConfigException; |
|
11
|
|
|
use Yiisoft\Db\Exception\StaleObjectException; |
|
12
|
|
|
use Yiisoft\Db\Expression\Expression; |
|
13
|
|
|
use Yiisoft\Db\Query\Query; |
|
14
|
|
|
use Yiisoft\Db\Schema\TableSchema; |
|
15
|
|
|
use Yiisoft\Strings\Inflector; |
|
16
|
|
|
use Yiisoft\Strings\StringHelper; |
|
17
|
|
|
|
|
18
|
|
|
use function array_diff; |
|
19
|
|
|
use function array_fill_keys; |
|
20
|
|
|
use function array_keys; |
|
21
|
|
|
use function array_map; |
|
22
|
|
|
use function array_values; |
|
23
|
|
|
use function in_array; |
|
24
|
|
|
use function is_array; |
|
25
|
|
|
use function is_string; |
|
26
|
|
|
use function key; |
|
27
|
|
|
use function preg_replace; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* ActiveRecord is the base class for classes representing relational data in terms of objects. |
|
31
|
|
|
* |
|
32
|
|
|
* Active Record implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record). |
|
33
|
|
|
* |
|
34
|
|
|
* The premise behind Active Record is that an individual {@see ActiveRecord} object is associated with a specific row |
|
35
|
|
|
* in a database table. The object's attributes are mapped to the columns of the corresponding table. |
|
36
|
|
|
* |
|
37
|
|
|
* Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record. |
|
38
|
|
|
* |
|
39
|
|
|
* As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table. |
|
40
|
|
|
* |
|
41
|
|
|
* This would mean that the class's `name` attribute is automatically mapped to the `name` column in `customer` table. |
|
42
|
|
|
* Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of the |
|
43
|
|
|
* `name` column for the table row, you can use the expression `$customer->name`. |
|
44
|
|
|
* |
|
45
|
|
|
* In this example, Active Record is providing an object-oriented interface for accessing data stored in the database. |
|
46
|
|
|
* But Active Record provides much more functionality than this. |
|
47
|
|
|
* |
|
48
|
|
|
* To declare an ActiveRecord class you need to extend {@see ActiveRecord} and implement the `tableName` method: |
|
49
|
|
|
* |
|
50
|
|
|
* ```php |
|
51
|
|
|
* <?php |
|
52
|
|
|
* |
|
53
|
|
|
* class Customer extends ActiveRecord |
|
54
|
|
|
* { |
|
55
|
|
|
* public function tableName(): string |
|
56
|
|
|
* { |
|
57
|
|
|
* return 'customer'; |
|
58
|
|
|
* } |
|
59
|
|
|
* } |
|
60
|
|
|
* ``` |
|
61
|
|
|
* |
|
62
|
|
|
* The `tableName` method only has to return the name of the database table associated with the class. |
|
63
|
|
|
* |
|
64
|
|
|
* Class instances are obtained in one of two ways: |
|
65
|
|
|
* |
|
66
|
|
|
* Using the `new` operator to create a new, empty object. |
|
67
|
|
|
* Using a method to fetch an existing record (or records) from the database. |
|
68
|
|
|
* |
|
69
|
|
|
* Below is an example showing some typical usage of ActiveRecord: |
|
70
|
|
|
* |
|
71
|
|
|
* ```php |
|
72
|
|
|
* $user = new User($db); |
|
73
|
|
|
* $user->name = 'Qiang'; |
|
74
|
|
|
* $user->save(); // a new row is inserted into user table |
|
75
|
|
|
* |
|
76
|
|
|
* // the following will retrieve the user 'CeBe' from the database |
|
77
|
|
|
* $user = ActiveQuery(User::class, $db); |
|
78
|
|
|
* $user = User->where(['name' => 'CeBe'])->one(); |
|
79
|
|
|
* |
|
80
|
|
|
* // this will get related records from orders table when relation is defined |
|
81
|
|
|
* $orders = $user->orders; |
|
82
|
|
|
* ``` |
|
83
|
|
|
* |
|
84
|
|
|
* For more details and usage information on ActiveRecord, |
|
85
|
|
|
* {@see the [guide article on ActiveRecord](guide:db-active-record)} |
|
86
|
|
|
* |
|
87
|
|
|
* @method ActiveQuery hasMany($class, array $link) {@see BaseActiveRecord::hasMany()} for more info. |
|
88
|
|
|
* @method ActiveQuery hasOne($class, array $link) {@see BaseActiveRecord::hasOne()} for more info. |
|
89
|
|
|
*/ |
|
90
|
|
|
class ActiveRecord extends BaseActiveRecord |
|
91
|
|
|
{ |
|
92
|
|
|
/** |
|
93
|
|
|
* The insert operation. This is mainly used when overriding {@see transactions()} to specify which operations are |
|
94
|
|
|
* transactional. |
|
95
|
|
|
*/ |
|
96
|
|
|
public const OP_INSERT = 0x01; |
|
97
|
|
|
|
|
98
|
|
|
/** |
|
99
|
|
|
* The update operation. This is mainly used when overriding {@see transactions()} to specify which operations are |
|
100
|
|
|
* transactional. |
|
101
|
|
|
*/ |
|
102
|
|
|
public const OP_UPDATE = 0x02; |
|
103
|
|
|
|
|
104
|
|
|
/** |
|
105
|
|
|
* The delete operation. This is mainly used when overriding {@see transactions()} to specify which operations are |
|
106
|
|
|
* transactional. |
|
107
|
|
|
*/ |
|
108
|
|
|
public const OP_DELETE = 0x04; |
|
109
|
|
|
|
|
110
|
|
|
/** |
|
111
|
|
|
* All three operations: insert, update, delete. |
|
112
|
|
|
* |
|
113
|
|
|
* This is a shortcut of the expression: OP_INSERT | OP_UPDATE | OP_DELETE. |
|
114
|
|
|
*/ |
|
115
|
|
|
public const OP_ALL = 0x07; |
|
116
|
|
|
|
|
117
|
|
|
/** |
|
118
|
|
|
* Loads default values from database table schema. |
|
119
|
|
|
* |
|
120
|
|
|
* You may call this method to load default values after creating a new instance: |
|
121
|
|
|
* |
|
122
|
|
|
* ```php |
|
123
|
|
|
* // class Customer extends ActiveRecord |
|
124
|
|
|
* $customer = new Customer($db); |
|
125
|
|
|
* $customer->loadDefaultValues(); |
|
126
|
|
|
* ``` |
|
127
|
|
|
* |
|
128
|
|
|
* @param bool $skipIfSet whether existing value should be preserved. This will only set defaults for attributes |
|
129
|
|
|
* that are `null`. |
|
130
|
|
|
* |
|
131
|
|
|
* @throws Exception|InvalidConfigException |
|
132
|
|
|
* |
|
133
|
|
|
* @return $this the model instance itself. |
|
134
|
|
|
*/ |
|
135
|
|
|
public function loadDefaultValues(bool $skipIfSet = true): self |
|
136
|
|
|
{ |
|
137
|
|
|
foreach ($this->getTableSchema()->getColumns() as $column) { |
|
138
|
|
|
if ($column->getDefaultValue() !== null && (!$skipIfSet || $this->{$column->getName()} === null)) { |
|
139
|
|
|
$this->{$column->getName()} = $column->getDefaultValue(); |
|
140
|
5 |
|
} |
|
141
|
|
|
} |
|
142
|
5 |
|
|
|
143
|
5 |
|
return $this; |
|
144
|
5 |
|
} |
|
145
|
|
|
|
|
146
|
|
|
/** |
|
147
|
|
|
* Returns table aliases which are not the same as the name of the tables. |
|
148
|
5 |
|
* |
|
149
|
|
|
* @param ActiveQuery $query |
|
150
|
|
|
* |
|
151
|
|
|
* @throws InvalidArgumentException|InvalidConfigException |
|
152
|
|
|
* |
|
153
|
|
|
* @return array |
|
154
|
|
|
*/ |
|
155
|
|
|
public function filterValidAliases(ActiveQuery $query): array |
|
156
|
|
|
{ |
|
157
|
|
|
$tables = $query->getTablesUsedInFrom(); |
|
158
|
|
|
|
|
159
|
|
|
$aliases = array_diff(array_keys($tables), $tables); |
|
160
|
|
|
|
|
161
|
|
|
return array_map(static function ($alias) { |
|
162
|
|
|
return preg_replace('/{{([\w]+)}}/', '$1', $alias); |
|
163
|
|
|
}, array_values($aliases)); |
|
164
|
|
|
} |
|
165
|
|
|
|
|
166
|
|
|
/** |
|
167
|
|
|
* Filters array condition before it is assigned to a Query filter. |
|
168
|
|
|
* |
|
169
|
8 |
|
* This method will ensure that an array condition only filters on existing table columns. |
|
170
|
|
|
* |
|
171
|
8 |
|
* @param array $condition condition to filter. |
|
172
|
|
|
* @param array $aliases |
|
173
|
|
|
* |
|
174
|
|
|
* @throws Exception|InvalidConfigException|InvalidArgumentException in case array contains unsafe values. |
|
175
|
|
|
* |
|
176
|
|
|
* @return array filtered condition. |
|
177
|
|
|
*/ |
|
178
|
|
|
public function filterCondition(array $condition, array $aliases = []): array |
|
179
|
|
|
{ |
|
180
|
|
|
$result = []; |
|
181
|
|
|
|
|
182
|
|
|
$columnNames = $this->filterValidColumnNames($aliases); |
|
183
|
|
|
|
|
184
|
|
|
foreach ($condition as $key => $value) { |
|
185
|
|
|
if (is_string($key) && !in_array($this->db->quoteSql($key), $columnNames, true)) { |
|
186
|
|
|
throw new InvalidArgumentException( |
|
187
|
|
|
'Key "' . $key . '" is not a column name and can not be used as a filter' |
|
188
|
253 |
|
); |
|
189
|
|
|
} |
|
190
|
253 |
|
$result[$key] = is_array($value) ? array_values($value) : $value; |
|
191
|
|
|
} |
|
192
|
253 |
|
|
|
193
|
157 |
|
return $result; |
|
194
|
|
|
} |
|
195
|
|
|
|
|
196
|
253 |
|
/** |
|
197
|
|
|
* Valid column names are table column names or column names prefixed with table name or table alias. |
|
198
|
161 |
|
* |
|
199
|
|
|
* @param array $aliases |
|
200
|
161 |
|
* |
|
201
|
161 |
|
* @throws Exception|InvalidConfigException |
|
202
|
|
|
* |
|
203
|
161 |
|
* @return array |
|
204
|
|
|
*/ |
|
205
|
|
|
protected function filterValidColumnNames(array $aliases): array |
|
206
|
|
|
{ |
|
207
|
|
|
$columnNames = []; |
|
208
|
|
|
$tableName = $this->tableName(); |
|
209
|
|
|
$quotedTableName = $this->db->quoteTableName($tableName); |
|
210
|
|
|
|
|
211
|
161 |
|
foreach ($this->getTableSchema()->getColumnNames() as $columnName) { |
|
212
|
|
|
$columnNames[] = $columnName; |
|
213
|
161 |
|
$columnNames[] = $this->db->quoteColumnName($columnName); |
|
214
|
|
|
$columnNames[] = "$tableName.$columnName"; |
|
215
|
104 |
|
$columnNames[] = $this->db->quoteSql("$quotedTableName.[[$columnName]]"); |
|
216
|
104 |
|
|
|
217
|
104 |
|
foreach ($aliases as $tableAlias) { |
|
218
|
|
|
$columnNames[] = "$tableAlias.$columnName"; |
|
219
|
|
|
$quotedTableAlias = $this->db->quoteTableName($tableAlias); |
|
220
|
221 |
|
$columnNames[] = $this->db->quoteSql("$quotedTableAlias.[[$columnName]]"); |
|
221
|
|
|
} |
|
222
|
|
|
} |
|
223
|
|
|
|
|
224
|
|
|
return $columnNames; |
|
225
|
|
|
} |
|
226
|
|
|
|
|
227
|
|
|
public function refresh(): bool |
|
228
|
|
|
{ |
|
229
|
|
|
$query = $this->instantiateQuery(); |
|
230
|
|
|
|
|
231
|
|
|
$tableName = key($query->getTablesUsedInFrom()); |
|
232
|
|
|
$pk = []; |
|
233
|
128 |
|
|
|
234
|
|
|
/** disambiguate column names in case ActiveQuery adds a JOIN */ |
|
235
|
128 |
|
foreach ($this->getPrimaryKey(true) as $key => $value) { |
|
236
|
|
|
$pk[$tableName . '.' . $key] = $value; |
|
237
|
128 |
|
} |
|
238
|
|
|
|
|
239
|
128 |
|
$query->where($pk); |
|
240
|
56 |
|
|
|
241
|
128 |
|
/** @var $record BaseActiveRecord */ |
|
242
|
|
|
$record = $query->one(); |
|
243
|
|
|
|
|
244
|
|
|
return $this->refreshInternal($record); |
|
245
|
|
|
} |
|
246
|
|
|
|
|
247
|
|
|
/** |
|
248
|
|
|
* Updates the whole table using the provided attribute values and conditions. |
|
249
|
|
|
* |
|
250
|
|
|
* For example, to change the status to be 1 for all customers whose status is 2: |
|
251
|
|
|
* |
|
252
|
|
|
* ```php |
|
253
|
|
|
* $customer = new Customer($db); |
|
254
|
|
|
* $customer->updateAll(['status' => 1], 'status = 2'); |
|
255
|
|
|
* ``` |
|
256
|
|
|
* |
|
257
|
|
|
* > Warning: If you do not specify any condition, this method will update **all** rows in the table. |
|
258
|
|
|
* |
|
259
|
104 |
|
* ```php |
|
260
|
|
|
* $customerQuery = new ActiveQuery(Customer::class, $db); |
|
261
|
104 |
|
* $aqClasses = $customerQuery->where('status = 2')->all(); |
|
262
|
|
|
* foreach ($aqClasses as $aqClass) { |
|
263
|
104 |
|
* $aqClass->status = 1; |
|
264
|
|
|
* $aqClass->update(); |
|
265
|
104 |
|
* } |
|
266
|
104 |
|
* ``` |
|
267
|
32 |
|
* |
|
268
|
32 |
|
* For a large set of models you might consider using {@see ActiveQuery::each()} to keep memory usage within limits. |
|
269
|
|
|
* |
|
270
|
|
|
* @param array $attributes attribute values (name-value pairs) to be saved into the table. |
|
271
|
72 |
|
* @param array|string $condition the conditions that will be put in the WHERE part of the UPDATE SQL. Please refer |
|
272
|
|
|
* to {@see Query::where()} on how to specify this parameter. |
|
273
|
|
|
* @param array $params the parameters (name => value) to be bound to the query. |
|
274
|
72 |
|
* |
|
275
|
|
|
* @throws Exception|InvalidConfigException|Throwable |
|
276
|
|
|
* |
|
277
|
|
|
* @return int the number of rows updated. |
|
278
|
|
|
*/ |
|
279
|
|
|
public function updateAll(array $attributes, $condition = '', array $params = []): int |
|
280
|
|
|
{ |
|
281
|
|
|
$command = $this->db->createCommand(); |
|
282
|
|
|
|
|
283
|
|
|
$command->update($this->tableName(), $attributes, $condition, $params); |
|
284
|
|
|
|
|
285
|
|
|
return $command->execute(); |
|
286
|
|
|
} |
|
287
|
|
|
|
|
288
|
104 |
|
/** |
|
289
|
|
|
* Updates the whole table using the provided counter changes and conditions. |
|
290
|
104 |
|
* |
|
291
|
104 |
|
* For example, to increment all customers' age by 1, |
|
292
|
104 |
|
* |
|
293
|
|
|
* ```php |
|
294
|
104 |
|
* $customer = new Customer($db); |
|
295
|
104 |
|
* $customer->updateAllCounters(['age' => 1]); |
|
296
|
104 |
|
* ``` |
|
297
|
104 |
|
* |
|
298
|
104 |
|
* Note that this method will not trigger any events. |
|
299
|
|
|
* |
|
300
|
104 |
|
* @param array $counters the counters to be updated (attribute name => increment value). |
|
301
|
44 |
|
* Use negative values if you want to decrement the counters. |
|
302
|
44 |
|
* @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL. Please refer |
|
303
|
44 |
|
* to {@see Query::where()} on how to specify this parameter. |
|
304
|
|
|
* @param array $params the parameters (name => value) to be bound to the query. |
|
305
|
|
|
* |
|
306
|
|
|
* Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method. |
|
307
|
104 |
|
* |
|
308
|
|
|
* @throws Exception|InvalidConfigException|Throwable |
|
309
|
|
|
* |
|
310
|
28 |
|
* @return int the number of rows updated. |
|
311
|
|
|
*/ |
|
312
|
28 |
|
public function updateAllCounters(array $counters, $condition = '', array $params = []): int |
|
313
|
|
|
{ |
|
314
|
28 |
|
$n = 0; |
|
315
|
28 |
|
|
|
316
|
|
|
foreach ($counters as $name => $value) { |
|
317
|
|
|
$counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]); |
|
318
|
28 |
|
$n++; |
|
319
|
28 |
|
} |
|
320
|
|
|
|
|
321
|
|
|
$command = $this->db->createCommand(); |
|
322
|
28 |
|
$command->update($this->tableName(), $counters, $condition, $params); |
|
323
|
|
|
|
|
324
|
|
|
return $command->execute(); |
|
325
|
28 |
|
} |
|
326
|
|
|
|
|
327
|
28 |
|
/** |
|
328
|
|
|
* Deletes rows in the table using the provided conditions. |
|
329
|
|
|
* |
|
330
|
|
|
* For example, to delete all customers whose status is 3: |
|
331
|
|
|
* |
|
332
|
|
|
* ```php |
|
333
|
|
|
* $customer = new Customer($this->db); |
|
334
|
|
|
* $customer->deleteAll('status = 3'); |
|
335
|
|
|
* ``` |
|
336
|
|
|
* |
|
337
|
|
|
* > Warning: If you do not specify any condition, this method will delete **all** rows in the table. |
|
338
|
|
|
* |
|
339
|
|
|
* ```php |
|
340
|
|
|
* $customerQuery = new ActiveQuery(Customer::class, $this->db); |
|
341
|
|
|
* $aqClasses = $customerQuery->where('status = 3')->all(); |
|
342
|
|
|
* foreach ($aqClasses as $aqClass) { |
|
343
|
|
|
* $aqClass->delete(); |
|
344
|
|
|
* } |
|
345
|
|
|
* ``` |
|
346
|
|
|
* |
|
347
|
|
|
* For a large set of models you might consider using {@see ActiveQuery::each()} to keep memory usage within limits. |
|
348
|
|
|
* |
|
349
|
|
|
* @param array|null $condition the conditions that will be put in the WHERE part of the DELETE SQL. Please refer |
|
350
|
|
|
* to {@see Query::where()} on how to specify this parameter. |
|
351
|
|
|
* @param array $params the parameters (name => value) to be bound to the query. |
|
352
|
|
|
* |
|
353
|
|
|
* @throws Exception|InvalidConfigException|Throwable |
|
354
|
|
|
* |
|
355
|
|
|
* @return int the number of rows deleted. |
|
356
|
|
|
*/ |
|
357
|
|
|
public function deleteAll(?array $condition = null, array $params = []): int |
|
358
|
|
|
{ |
|
359
|
|
|
$command = $this->db->createCommand(); |
|
360
|
|
|
$command->delete($this->tableName(), $condition, $params); |
|
361
|
|
|
|
|
362
|
|
|
return $command->execute(); |
|
363
|
|
|
} |
|
364
|
|
|
|
|
365
|
|
|
/** |
|
366
|
|
|
* Declares the name of the database table associated with this active record class. |
|
367
|
46 |
|
* |
|
368
|
|
|
* By default this method returns the class name as the table name by calling {@see Inflector::pascalCaseToId()} |
|
369
|
46 |
|
* with prefix {@see Connection::tablePrefix}. For example if {@see Connection::tablePrefix} is `tbl_`, `Customer` |
|
370
|
|
|
* becomes `tbl_customer`, and `OrderItem` becomes `tbl_order_item`. You may override this method if the table is |
|
371
|
46 |
|
* not named after this convention. |
|
372
|
|
|
* |
|
373
|
46 |
|
* @return string the table name. |
|
374
|
|
|
*/ |
|
375
|
|
|
public function tableName(): string |
|
376
|
|
|
{ |
|
377
|
|
|
$inflector = new Inflector(); |
|
378
|
|
|
|
|
379
|
|
|
return '{{%' . $inflector->pascalCaseToId(StringHelper::baseName(static::class), '_') . '}}'; |
|
380
|
|
|
} |
|
381
|
|
|
|
|
382
|
|
|
/** |
|
383
|
|
|
* Returns the schema information of the DB table associated with this AR class. |
|
384
|
|
|
* |
|
385
|
|
|
* @throws Exception |
|
386
|
|
|
* @throws InvalidConfigException if the table for the AR class does not exist. |
|
387
|
|
|
* |
|
388
|
|
|
* @return TableSchema the schema information of the DB table associated with this AR class. |
|
389
|
|
|
*/ |
|
390
|
|
|
public function getTableSchema(): TableSchema |
|
391
|
|
|
{ |
|
392
|
|
|
$tableSchema = $this->db->getSchema()->getTableSchema($this->tableName()); |
|
393
|
|
|
|
|
394
|
|
|
if ($tableSchema === null) { |
|
395
|
|
|
throw new InvalidConfigException('The table does not exist: ' . $this->tableName()); |
|
396
|
|
|
} |
|
397
|
|
|
|
|
398
|
|
|
return $tableSchema; |
|
399
|
|
|
} |
|
400
|
|
|
|
|
401
|
|
|
/** |
|
402
|
8 |
|
* Returns the primary key name(s) for this AR class. |
|
403
|
|
|
* |
|
404
|
8 |
|
* The default implementation will return the primary key(s) as declared in the DB table that is associated with |
|
405
|
|
|
* this AR class. |
|
406
|
8 |
|
* |
|
407
|
8 |
|
* If the DB table does not declare any primary key, you should override this method to return the attributes that |
|
408
|
8 |
|
* you want to use as primary keys for this AR class. |
|
409
|
|
|
* |
|
410
|
|
|
* Note that an array should be returned even for a table with single primary key. |
|
411
|
8 |
|
* |
|
412
|
8 |
|
* @throws Exception |
|
413
|
|
|
* @throws InvalidConfigException |
|
414
|
8 |
|
* |
|
415
|
|
|
* @return string[] the primary keys of the associated database table. |
|
416
|
|
|
*/ |
|
417
|
|
|
public function primaryKey(): array |
|
418
|
|
|
{ |
|
419
|
|
|
return $this->getTableSchema()->getPrimaryKey(); |
|
420
|
|
|
} |
|
421
|
|
|
|
|
422
|
|
|
/** |
|
423
|
|
|
* Returns the list of all attribute names of the model. |
|
424
|
|
|
* |
|
425
|
|
|
* The default implementation will return all column names of the table associated with this AR class. |
|
426
|
|
|
* |
|
427
|
|
|
* @return array list of attribute names. |
|
428
|
|
|
* |
|
429
|
|
|
* @throws InvalidConfigException |
|
430
|
|
|
* |
|
431
|
|
|
* @throws Exception |
|
432
|
|
|
*/ |
|
433
|
|
|
public function attributes(): array |
|
434
|
|
|
{ |
|
435
|
|
|
return array_keys($this->getTableSchema()->getColumns()); |
|
436
|
|
|
} |
|
437
|
|
|
|
|
438
|
|
|
/** |
|
439
|
|
|
* Declares which DB operations should be performed within a transaction in different scenarios. |
|
440
|
|
|
* |
|
441
|
|
|
* The supported DB operations are: {@see OP_INSERT}, {@see OP_UPDATE} and {@see OP_DELETE}, which correspond to the |
|
442
|
|
|
* {@see insert()}, {@see update()} and {@see delete()} methods, respectively. |
|
443
|
|
|
* |
|
444
|
|
|
* By default, these methods are NOT enclosed in a DB transaction. |
|
445
|
|
|
* |
|
446
|
|
|
* In some scenarios, to ensure data consistency, you may want to enclose some or all of them in transactions. You |
|
447
|
|
|
* can do so by overriding this method and returning the operations that need to be transactional. For example, |
|
448
|
|
|
* |
|
449
|
|
|
* ```php |
|
450
|
|
|
* return [ |
|
451
|
|
|
* 'admin' => self::OP_INSERT, |
|
452
|
20 |
|
* 'api' => self::OP_INSERT | self::OP_UPDATE | self::OP_DELETE, |
|
453
|
|
|
* // the above is equivalent to the following: |
|
454
|
20 |
|
* // 'api' => self::OP_ALL, |
|
455
|
20 |
|
* |
|
456
|
|
|
* ]; |
|
457
|
20 |
|
* ``` |
|
458
|
|
|
* |
|
459
|
|
|
* The above declaration specifies that in the "admin" scenario, the insert operation ({@see insert()}) should be |
|
460
|
|
|
* done in a transaction; and in the "api" scenario, all the operations should be done in a transaction. |
|
461
|
|
|
* |
|
462
|
|
|
* @return array the declarations of transactional operations. The array keys are scenarios names, and the array |
|
463
|
276 |
|
* values are the corresponding transaction operations. |
|
464
|
|
|
*/ |
|
465
|
276 |
|
public function transactions(): array |
|
466
|
|
|
{ |
|
467
|
|
|
return []; |
|
468
|
|
|
} |
|
469
|
|
|
|
|
470
|
|
|
/** |
|
471
|
|
|
* Populates an active record object using a row of data from the database/storage. |
|
472
|
|
|
* |
|
473
|
|
|
* This is an internal method meant to be called to create active record objects after fetching data from the |
|
474
|
|
|
* database. It is mainly used by {@see ActiveQuery} to populate the query results into active records. |
|
475
|
|
|
* |
|
476
|
|
|
* @param ActiveRecordInterface|array $record the record to be populated. In most cases this will be an instance |
|
477
|
|
|
* created by {@see instantiate()} beforehand. |
|
478
|
14 |
|
* @param array|object $row attribute values (name => value). |
|
479
|
|
|
* |
|
480
|
14 |
|
* @throws Exception|InvalidConfigException |
|
481
|
|
|
*/ |
|
482
|
|
|
public function populateRecord($record, $row): void |
|
483
|
|
|
{ |
|
484
|
|
|
$columns = $this->getTableSchema()->getColumns(); |
|
485
|
|
|
|
|
486
|
|
|
foreach ($row as $name => $value) { |
|
487
|
|
|
if (isset($columns[$name])) { |
|
488
|
|
|
$row[$name] = $columns[$name]->phpTypecast($value); |
|
489
|
|
|
} |
|
490
|
|
|
} |
|
491
|
445 |
|
|
|
492
|
|
|
parent::populateRecord($record, $row); |
|
493
|
445 |
|
} |
|
494
|
445 |
|
|
|
495
|
445 |
|
/** |
|
496
|
|
|
* Inserts a row into the associated database table using the attribute values of this record. |
|
497
|
445 |
|
* |
|
498
|
|
|
* Only the {@see dirtyAttributes|changed attribute values} will be inserted into database. |
|
499
|
|
|
* |
|
500
|
|
|
* If the table's primary key is auto-incremental and is `null` during insertion, it will be populated with the |
|
501
|
445 |
|
* actual value after insertion. |
|
502
|
|
|
* |
|
503
|
|
|
* For example, to insert a customer record: |
|
504
|
|
|
* |
|
505
|
|
|
* ```php |
|
506
|
|
|
* $customer = new Customer($db); |
|
507
|
|
|
* $customer->name = $name; |
|
508
|
|
|
* $customer->email = $email; |
|
509
|
|
|
* $customer->insert(); |
|
510
|
|
|
* ``` |
|
511
|
|
|
* |
|
512
|
|
|
* @param array|null $attributes list of attributes that need to be saved. Defaults to `null`, meaning all |
|
513
|
|
|
* attributes that are loaded from DB will be saved. |
|
514
|
|
|
* |
|
515
|
|
|
* @throws InvalidConfigException|Throwable in case insert failed. |
|
516
|
|
|
* |
|
517
|
|
|
* @return bool whether the attributes are valid and the record is inserted successfully. |
|
518
|
|
|
*/ |
|
519
|
|
|
public function insert(array $attributes = null): bool |
|
520
|
224 |
|
{ |
|
521
|
|
|
if (!$this->isTransactional(self::OP_INSERT)) { |
|
522
|
224 |
|
return $this->insertInternal($attributes); |
|
523
|
|
|
} |
|
524
|
|
|
|
|
525
|
|
|
$transaction = $this->db->beginTransaction(); |
|
526
|
|
|
|
|
527
|
|
|
try { |
|
528
|
|
|
$result = $this->insertInternal($attributes); |
|
529
|
|
|
if ($result === false) { |
|
530
|
|
|
$transaction->rollBack(); |
|
531
|
|
|
} else { |
|
532
|
|
|
$transaction->commit(); |
|
533
|
|
|
} |
|
534
|
|
|
|
|
535
|
|
|
return $result; |
|
536
|
361 |
|
} catch (Throwable $e) { |
|
537
|
|
|
$transaction->rollBack(); |
|
538
|
361 |
|
throw $e; |
|
539
|
|
|
} |
|
540
|
|
|
} |
|
541
|
|
|
|
|
542
|
|
|
/** |
|
543
|
|
|
* Inserts an ActiveRecord into DB without considering transaction. |
|
544
|
|
|
* |
|
545
|
|
|
* @param array|null $attributes list of attributes that need to be saved. Defaults to `null`, meaning all |
|
546
|
|
|
* attributes that are loaded from DB will be saved. |
|
547
|
|
|
* |
|
548
|
|
|
* @throws Exception|InvalidArgumentException|InvalidConfigException |
|
549
|
|
|
* |
|
550
|
|
|
* @return bool whether the record is inserted successfully. |
|
551
|
|
|
*/ |
|
552
|
|
|
protected function insertInternal(?array $attributes = null): bool |
|
553
|
|
|
{ |
|
554
|
|
|
$values = $this->getDirtyAttributes($attributes); |
|
555
|
|
|
|
|
556
|
|
|
if (($primaryKeys = $this->db->getSchema()->insert($this->tableName(), $values)) === false) { |
|
557
|
|
|
return false; |
|
558
|
|
|
} |
|
559
|
|
|
|
|
560
|
|
|
foreach ($primaryKeys as $name => $value) { |
|
561
|
|
|
$id = $this->getTableSchema()->getColumn($name)->phpTypecast($value); |
|
562
|
|
|
$this->setAttribute($name, $id); |
|
563
|
|
|
$values[$name] = $id; |
|
564
|
|
|
} |
|
565
|
|
|
|
|
566
|
|
|
$changedAttributes = array_fill_keys(array_keys($values), null); |
|
|
|
|
|
|
567
|
|
|
|
|
568
|
81 |
|
$this->setOldAttributes($values); |
|
569
|
|
|
|
|
570
|
81 |
|
return true; |
|
571
|
|
|
} |
|
572
|
|
|
|
|
573
|
|
|
/** |
|
574
|
|
|
* Saves the changes to this active record into the associated database table. |
|
575
|
|
|
* |
|
576
|
|
|
* Only the {@see dirtyAttributes|changed attribute values} will be saved into database. |
|
577
|
|
|
* |
|
578
|
|
|
* For example, to update a customer record: |
|
579
|
|
|
* |
|
580
|
|
|
* ```php |
|
581
|
|
|
* $customer = new Customer($db); |
|
582
|
|
|
* $customer->name = $name; |
|
583
|
|
|
* $customer->email = $email; |
|
584
|
|
|
* $customer->update(); |
|
585
|
|
|
* ``` |
|
586
|
|
|
* |
|
587
|
|
|
* Note that it is possible the update does not affect any row in the table. In this case, this method will return |
|
588
|
|
|
* 0. For this reason, you should use the following code to check if update() is successful or not: |
|
589
|
328 |
|
* |
|
590
|
|
|
* ```php |
|
591
|
328 |
|
* if ($customer->update() !== false) { |
|
592
|
|
|
* // update successful |
|
593
|
328 |
|
* } else { |
|
594
|
328 |
|
* // update failed |
|
595
|
328 |
|
* } |
|
596
|
|
|
* ``` |
|
597
|
|
|
* |
|
598
|
|
|
* @param array|null $attributeNames list of attributes that need to be saved. Defaults to `null`, meaning all |
|
599
|
328 |
|
* attributes that are loaded from DB will be saved. |
|
600
|
328 |
|
* |
|
601
|
|
|
* @throws StaleObjectException if {@see optimisticLock|optimistic locking} is enabled and the data being updated is |
|
602
|
|
|
* outdated. |
|
603
|
|
|
* @throws Throwable in case update failed. |
|
604
|
|
|
* |
|
605
|
|
|
* @return bool|int the number of rows affected, or false if validation fails or {@seebeforeSave()} stops the |
|
606
|
|
|
* updating process. |
|
607
|
|
|
*/ |
|
608
|
|
|
public function update(?array $attributeNames = null) |
|
609
|
|
|
{ |
|
610
|
|
|
if (!$this->isTransactional(self::OP_UPDATE)) { |
|
611
|
|
|
return $this->updateInternal($attributeNames); |
|
612
|
|
|
} |
|
613
|
|
|
|
|
614
|
|
|
$transaction = $this->db->beginTransaction(); |
|
615
|
|
|
|
|
616
|
|
|
try { |
|
617
|
|
|
$result = $this->updateInternal($attributeNames); |
|
618
|
|
|
if ($result === false) { |
|
|
|
|
|
|
619
|
|
|
$transaction->rollBack(); |
|
620
|
|
|
} else { |
|
621
|
|
|
$transaction->commit(); |
|
622
|
|
|
} |
|
623
|
|
|
|
|
624
|
|
|
return $result; |
|
625
|
|
|
} catch (Throwable $e) { |
|
626
|
|
|
$transaction->rollBack(); |
|
627
|
|
|
throw $e; |
|
628
|
|
|
} |
|
629
|
|
|
} |
|
630
|
|
|
|
|
631
|
|
|
/** |
|
632
|
|
|
* Deletes the table row corresponding to this active record. |
|
633
|
|
|
* |
|
634
|
|
|
* @throws StaleObjectException if {@see optimisticLock|optimistic locking} is enabled and the data being deleted |
|
635
|
|
|
* is outdated. |
|
636
|
|
|
* @throws Throwable in case delete failed. |
|
637
|
|
|
* |
|
638
|
|
|
* @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason. |
|
639
|
|
|
* |
|
640
|
61 |
|
* Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
|
641
|
|
|
*/ |
|
642
|
61 |
|
public function delete() |
|
643
|
61 |
|
{ |
|
644
|
|
|
if (!$this->isTransactional(self::OP_DELETE)) { |
|
645
|
|
|
return $this->deleteInternal(); |
|
646
|
|
|
} |
|
647
|
|
|
|
|
648
|
|
|
$transaction = $this->db->beginTransaction(); |
|
649
|
|
|
|
|
650
|
|
|
try { |
|
651
|
|
|
$result = $this->deleteInternal(); |
|
652
|
|
|
if ($result === false) { |
|
|
|
|
|
|
653
|
|
|
$transaction->rollBack(); |
|
654
|
|
|
} else { |
|
655
|
|
|
$transaction->commit(); |
|
656
|
|
|
} |
|
657
|
|
|
|
|
658
|
|
|
return $result; |
|
659
|
|
|
} catch (Throwable $e) { |
|
660
|
|
|
$transaction->rollBack(); |
|
661
|
|
|
throw $e; |
|
662
|
|
|
} |
|
663
|
|
|
} |
|
664
|
|
|
|
|
665
|
|
|
/** |
|
666
|
|
|
* Deletes an ActiveRecord without considering transaction. |
|
667
|
|
|
* |
|
668
|
|
|
* Note that it is possible the number of rows deleted is 0, even though the deletion execution is successful. |
|
669
|
|
|
* |
|
670
|
|
|
* @throws Exception|StaleObjectException|Throwable |
|
671
|
|
|
* |
|
672
|
|
|
* @return int|false the number of rows deleted, or `false` if the deletion is unsuccessful for some reason. |
|
673
|
|
|
*/ |
|
674
|
|
|
protected function deleteInternal() |
|
675
|
61 |
|
{ |
|
676
|
|
|
/** |
|
677
|
61 |
|
* we do not check the return value of deleteAll() because it's possible the record is already deleted in the |
|
678
|
|
|
* database and thus the method will return 0. |
|
679
|
61 |
|
*/ |
|
680
|
|
|
$condition = $this->getOldPrimaryKey(true); |
|
681
|
|
|
|
|
682
|
|
|
$lock = $this->optimisticLock(); |
|
|
|
|
|
|
683
|
61 |
|
|
|
684
|
57 |
|
if ($lock !== null) { |
|
|
|
|
|
|
685
|
57 |
|
$condition[$lock] = $this->$lock; |
|
686
|
57 |
|
} |
|
687
|
|
|
|
|
688
|
|
|
$result = $this->deleteAll($condition); |
|
689
|
61 |
|
|
|
690
|
|
|
if ($lock !== null && !$result) { |
|
|
|
|
|
|
691
|
61 |
|
throw new StaleObjectException('The object being deleted is outdated.'); |
|
692
|
|
|
} |
|
693
|
61 |
|
|
|
694
|
|
|
$this->setOldAttributes(null); |
|
695
|
|
|
|
|
696
|
|
|
return $result; |
|
697
|
|
|
} |
|
698
|
|
|
|
|
699
|
|
|
/** |
|
700
|
|
|
* Returns a value indicating whether the given active record is the same as the current one. |
|
701
|
|
|
* |
|
702
|
|
|
* The comparison is made by comparing the table names and the primary key values of the two active records. If one |
|
703
|
|
|
* of the records {@see isNewRecord|is new} they are also considered not equal. |
|
704
|
|
|
* |
|
705
|
|
|
* @param ActiveRecordInterface $record record to compare to. |
|
706
|
|
|
* |
|
707
|
|
|
* @return bool whether the two active records refer to the same row in the same database table. |
|
708
|
|
|
*/ |
|
709
|
|
|
public function equals(ActiveRecordInterface $record): bool |
|
710
|
|
|
{ |
|
711
|
|
|
if ($this->isNewRecord || $record->isNewRecord) { |
|
|
|
|
|
|
712
|
|
|
return false; |
|
713
|
|
|
} |
|
714
|
|
|
|
|
715
|
|
|
return $this->tableName() === $record->tableName() && $this->getPrimaryKey() === $record->getPrimaryKey(); |
|
|
|
|
|
|
716
|
|
|
} |
|
717
|
|
|
|
|
718
|
|
|
/** |
|
719
|
|
|
* Returns a value indicating whether the specified operation is transactional in the current {@see $scenario}. |
|
720
|
|
|
* |
|
721
|
|
|
* @param int $operation the operation to check. Possible values are {@see OP_INSERT}, {@see OP_UPDATE} and |
|
722
|
|
|
* {@see OP_DELETE}. |
|
723
|
|
|
* |
|
724
|
|
|
* @return array|bool whether the specified operation is transactional in the current {@see scenario}. |
|
725
|
|
|
*/ |
|
726
|
|
|
public function isTransactional(int $operation) |
|
|
|
|
|
|
727
|
|
|
{ |
|
728
|
|
|
return $this->transactions(); |
|
729
|
|
|
} |
|
730
|
|
|
} |
|
731
|
|
|
|