ActiveRecord.md 13.6 KB
Newer Older
Qiang Xue committed
1
ActiveRecord implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record).
2
The idea is that an ActiveRecord object is associated with a row in a database table
Alexander Mohorev committed
3
so object properties are mapped to columns of the corresponding database row.
4 5 6
For example, a `Customer` object is associated with a row in the `tbl_customer`
table. Instead of writing raw SQL statements to access the data in the table,
you can call intuitive methods available in the corresponding ActiveRecord class
Qiang Xue committed
7
to achieve the same goals. For example, calling [[save()]] would insert or update a row
8 9 10 11 12 13 14
in the underlying table:

~~~
$customer = new Customer();
$customer->name = 'Qiang';
$customer->save();
~~~
Qiang Xue committed
15

Qiang Xue committed
16 17 18

### Declaring ActiveRecord Classes

19 20
To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and
implement `tableName` method like the following:
Qiang Xue committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

~~~
class Customer extends \yii\db\ActiveRecord
{
	/**
	 * @return string the name of the table associated with this ActiveRecord class.
	 */
	public static function tableName()
	{
		return 'tbl_customer';
	}
}
~~~

### Connecting to Database

37 38 39 40
ActiveRecord relies on a [[Connection|DB connection]]. By default, it assumes that
there is an application component named `db` that gives the needed [[Connection]]
instance which serves as the DB connection. Usually this component is configured
via application configuration like the following:
Qiang Xue committed
41 42

~~~
Alexander Makarov committed
43 44 45
return [
	'components' => [
		'db' => [
Qiang Xue committed
46 47 48 49 50 51
			'class' => 'yii\db\Connection',
			'dsn' => 'mysql:host=localhost;dbname=testdb',
			'username' => 'demo',
			'password' => 'demo',
			// turn on schema caching to improve performance
			// 'schemaCacheDuration' => 3600,
Alexander Makarov committed
52 53 54
		],
	],
];
Qiang Xue committed
55 56 57
~~~


58
### Getting Data from Database
Qiang Xue committed
59

60
There are two ActiveRecord methods for getting data:
Qiang Xue committed
61 62 63 64

- [[find()]]
- [[findBySql()]]

65
They both return an [[ActiveQuery]] instance. Coupled with the various customization and query methods
Qiang Xue committed
66 67 68 69 70 71 72
provided by [[ActiveQuery]], ActiveRecord supports very flexible and powerful data retrieval approaches.

The followings are some examples,

~~~
// to retrieve all *active* customers and order them by their ID:
$customers = Customer::find()
Alexander Makarov committed
73
	->where(['status' => $active])
Qiang Xue committed
74 75 76 77 78
	->orderBy('id')
	->all();

// to return a single customer whose ID is 1:
$customer = Customer::find()
Alexander Makarov committed
79
	->where(['id' => 1])
Qiang Xue committed
80 81 82 83 84 85 86 87 88 89
	->one();

// or use the following shortcut approach:
$customer = Customer::find(1);

// to retrieve customers using a raw SQL statement:
$sql = 'SELECT * FROM tbl_customer';
$customers = Customer::findBySql($sql)->all();

// to return the number of *active* customers:
90
$count = Customer::find()
Alexander Makarov committed
91
	->where(['status' => $active])
92
	->count();
Qiang Xue committed
93 94 95 96 97 98 99 100 101 102 103 104 105

// to return customers in terms of arrays rather than `Customer` objects:
$customers = Customer::find()->asArray()->all();
// each $customers element is an array of name-value pairs

// to index the result by customer IDs:
$customers = Customer::find()->indexBy('id')->all();
// $customers array is indexed by customer IDs
~~~


### Accessing Column Data

106
ActiveRecord maps each column of the corresponding database table row to an *attribute* in the ActiveRecord
Qiang Xue committed
107 108 109 110 111 112 113 114 115 116 117 118
object. An attribute is like a regular object property whose name is the same as the corresponding column
name and is case sensitive.

To read the value of a column, we can use the following expression:

~~~
// "id" is the name of a column in the table associated with $customer ActiveRecord object
$id = $customer->id;
// or alternatively,
$id = $customer->getAttribute('id');
~~~

119
We can get all column values through the [[attributes]] property:
Qiang Xue committed
120 121 122 123 124 125 126 127

~~~
$values = $customer->attributes;
~~~


### Persisting Data to Database

128
ActiveRecord provides the following methods to insert, update and delete data:
Qiang Xue committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

- [[save()]]
- [[insert()]]
- [[update()]]
- [[delete()]]
- [[updateCounters()]]
- [[updateAll()]]
- [[updateAllCounters()]]
- [[deleteAll()]]

Note that [[updateAll()]], [[updateAllCounters()]] and [[deleteAll()]] apply to the whole database
table, while the rest of the methods only apply to the row associated with the ActiveRecord object.

The followings are some examples:

~~~
// to insert a new customer record
$customer = new Customer;
$customer->name = 'James';
$customer->email = 'james@example.com';
$customer->save();  // equivalent to $customer->insert();

// to update an existing customer record
$customer = Customer::find($id);
$customer->email = 'james@example.com';
$customer->save();  // equivalent to $customer->update();

// to delete an existing customer record
$customer = Customer::find($id);
$customer->delete();

// to increment the age of all customers by 1
Alexander Makarov committed
161
Customer::updateAllCounters(['age' => 1]);
Qiang Xue committed
162 163 164
~~~


165
### Getting Relational Data
Qiang Xue committed
166

167 168
Using ActiveRecord you can expose relationships as properties. For example,
with an appropriate declaration, `$customer->orders` can return an array of `Order` objects
Qiang Xue committed
169 170 171 172 173 174 175 176 177
which represent the orders placed by the specified customer.

To declare a relationship, define a getter method which returns an [[ActiveRelation]] object. For example,

~~~
class Customer extends \yii\db\ActiveRecord
{
	public function getOrders()
	{
178
		return $this->hasMany(Order::className(), ['customer_id' => 'id']);
Qiang Xue committed
179 180 181 182 183 184 185
	}
}

class Order extends \yii\db\ActiveRecord
{
	public function getCustomer()
	{
186
		return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
Qiang Xue committed
187 188 189 190
	}
}
~~~

191 192 193 194
Within the getter methods above, we call [[hasMany()]] or [[hasOne()]] methods to
create a new [[ActiveRelation]] object. The [[hasMany()]] method declares
a one-many relationship. For example, a customer has many orders. And the [[hasOne()]]
method declares a many-one or one-one relationship. For example, an order has one customer.
Qiang Xue committed
195 196
Both methods take two parameters:

197
- `$class`: the name of the class that the related models should use.
Qiang Xue committed
198 199
- `$link`: the association between columns from two tables. This should be given as an array.
  The keys of the array are the names of the columns from the table associated with `$class`,
200 201
  while the values of the array are the names of the columns from the declaring class.
  It is a good practice to define relationships based on table foreign keys.
Qiang Xue committed
202

203 204
After declaring relationships getting relational data is as easy as accessing
a component property that is defined by the getter method:
Qiang Xue committed
205 206

~~~
207
// the orders of a customer
Qiang Xue committed
208 209
$customer = Customer::find($id);
$orders = $customer->orders;  // $orders is an array of Order objects
210 211

// the customer of the first order
Qiang Xue committed
212 213 214
$customer2 = $orders[0]->customer;  // $customer == $customer2
~~~

215 216 217 218
Because [[ActiveRelation]] extends from [[ActiveQuery]], it has the same query building methods,
which allows us to customize the query for retrieving the related objects.
For example, we may declare a `bigOrders` relationship which returns orders whose
subtotal exceeds certain amount:
Qiang Xue committed
219 220 221 222

~~~
class Customer extends \yii\db\ActiveRecord
{
223
	public function getBigOrders($threshold = 100)
Qiang Xue committed
224
	{
225
		return $this->hasMany(Order::className(), ['customer_id' => 'id'])
Alexander Makarov committed
226
			->where('subtotal > :threshold', [':threshold' => $threshold])
Qiang Xue committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
			->orderBy('id');
	}
}
~~~


Sometimes, two tables are related together via an intermediary table called
[pivot table](http://en.wikipedia.org/wiki/Pivot_table). To declare such relationships, we can customize
the [[ActiveRelation]] object by calling its [[ActiveRelation::via()]] or [[ActiveRelation::viaTable()]]
method.

For example, if table `tbl_order` and table `tbl_item` are related via pivot table `tbl_order_item`,
we can declare the `items` relation in the `Order` class like the following:

~~~
class Order extends \yii\db\ActiveRecord
{
	public function getItems()
	{
246
		return $this->hasMany(Item::className(), ['id' => 'item_id'])
Alexander Makarov committed
247
			->viaTable('tbl_order_item', ['order_id' => 'id']);
Qiang Xue committed
248 249 250 251
	}
}
~~~

252
[[ActiveRelation::via()]] method is similar to [[ActiveRelation::viaTable()]] except that
Qiang Xue committed
253 254 255 256 257 258 259 260
the first parameter of [[ActiveRelation::via()]] takes a relation name declared in the ActiveRecord class.
For example, the above `items` relation can be equivalently declared as follows:

~~~
class Order extends \yii\db\ActiveRecord
{
	public function getOrderItems()
	{
261
		return $this->hasMany(OrderItem::className(), ['order_id' => 'id']);
Qiang Xue committed
262 263 264 265
	}

	public function getItems()
	{
266
		return $this->hasMany(Item::className(), ['id' => 'item_id'])
Qiang Xue committed
267 268 269 270 271 272
			->via('orderItems');
	}
}
~~~


273 274 275
When you access the related objects the first time, behind the scene ActiveRecord performs a DB query
to retrieve the corresponding data and populate it into the related objects. No query will be performed
if you access the same related objects again. We call this *lazy loading*. For example,
Qiang Xue committed
276 277 278 279 280 281 282 283 284 285 286

~~~
// SQL executed: SELECT * FROM tbl_customer WHERE id=1
$customer = Customer::find(1);
// SQL executed: SELECT * FROM tbl_order WHERE customer_id=1
$orders = $customer->orders;
// no SQL executed
$orders2 = $customer->orders;
~~~


287 288
Lazy loading is very convenient to use. However, it may suffer from performance
issue in the following scenario:
Qiang Xue committed
289 290 291 292 293 294 295 296 297 298 299 300 301

~~~
// SQL executed: SELECT * FROM tbl_customer LIMIT 100
$customers = Customer::find()->limit(100)->all();

foreach ($customers as $customer) {
	// SQL executed: SELECT * FROM tbl_order WHERE customer_id=...
	$orders = $customer->orders;
	// ...handle $orders...
}
~~~

How many SQL queries will be performed in the above code, assuming there are more than 100 customers in
Qiang Xue committed
302
the database? 101! The first SQL query brings back 100 customers. Then for each customer, a SQL query
Qiang Xue committed
303 304
is performed to bring back the customer's orders.

305
To solve the above performance problem, you can use the so-called *eager loading* by calling [[ActiveQuery::with()]]:
Qiang Xue committed
306 307 308 309 310 311 312 313 314 315 316 317 318 319

~~~
// SQL executed: SELECT * FROM tbl_customer LIMIT 100
//               SELECT * FROM tbl_orders WHERE customer_id IN (1,2,...)
$customers = Customer::find()->limit(100)
	->with('orders')->all();

foreach ($customers as $customer) {
	// no SQL executed
	$orders = $customer->orders;
	// ...handle $orders...
}
~~~

Qiang Xue committed
320
As you can see, only two SQL queries are needed for the same task.
Qiang Xue committed
321 322


323 324
Sometimes, you may want to customize the relational queries on the fly. It can be
done for both lazy loading and eager loading. For example,
Qiang Xue committed
325 326 327 328 329 330 331 332

~~~
$customer = Customer::find(1);
// lazy loading: SELECT * FROM tbl_order WHERE customer_id=1 AND subtotal>100
$orders = $customer->getOrders()->where('subtotal>100')->all();

// eager loading: SELECT * FROM tbl_customer LIMIT 10
                  SELECT * FROM tbl_order WHERE customer_id IN (1,2,...) AND subtotal>100
Alexander Makarov committed
333
$customers = Customer::find()->limit(100)->with([
Qiang Xue committed
334 335 336
	'orders' => function($query) {
		$query->andWhere('subtotal>100');
	},
Alexander Makarov committed
337
])->all();
Qiang Xue committed
338 339 340
~~~


341
### Working with Relationships
Qiang Xue committed
342

343 344
ActiveRecord provides the following two methods for establishing and breaking a
relationship between two ActiveRecord objects:
Qiang Xue committed
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364

- [[link()]]
- [[unlink()]]

For example, given a customer and a new order, we can use the following code to make the
order owned by the customer:

~~~
$customer = Customer::find(1);
$order = new Order;
$order->subtotal = 100;
$customer->link('orders', $order);
~~~

The [[link()]] call above will set the `customer_id` of the order to be the primary key
value of `$customer` and then call [[save()]] to save the order into database.


### Data Input and Validation

365 366 367 368 369 370 371 372 373 374 375 376
TBD


### Life Cycles of an ActiveRecord Object

An ActiveRecord object undergoes different life cycles when it is used in different cases.
Subclasses or ActiveRecord behaviors may "inject" custom code in these life cycles through
method overriding and event handling mechanisms.

When instantiating a new ActiveRecord instance, we will have the following life cycles:

1. constructor
Qiang Xue committed
377
2. [[init()]]: will trigger an [[EVENT_INIT]] event
378 379 380 381

When getting an ActiveRecord instance through the [[find()]] method, we will have the following life cycles:

1. constructor
Qiang Xue committed
382 383
2. [[init()]]: will trigger an [[EVENT_INIT]] event
3. [[afterFind()]]: will trigger an [[EVENT_AFTER_FIND]] event
384 385 386

When calling [[save()]] to insert or update an ActiveRecord, we will have the following life cycles:

Qiang Xue committed
387
1. [[beforeValidate()]]: will trigger an [[EVENT_BEFORE_VALIDATE]] event
388 389 390 391
2. [[afterValidate()]]: will trigger an [[EVENT_AFTER_VALIDATE]] event
3. [[beforeSave()]]: will trigger an [[EVENT_BEFORE_INSERT]] or [[EVENT_BEFORE_UPDATE]] event
4. perform the actual data insertion or updating
5. [[afterSave()]]: will trigger an [[EVENT_AFTER_INSERT]] or [[EVENT_AFTER_UPDATE]] event
392 393 394

Finally when calling [[delete()]] to delete an ActiveRecord, we will have the following life cycles:

Qiang Xue committed
395
1. [[beforeDelete()]]: will trigger an [[EVENT_BEFORE_DELETE]] event
396
2. perform the actual data deletion
Qiang Xue committed
397
3. [[afterDelete()]]: will trigger an [[EVENT_AFTER_DELETE]] event
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413


### Scopes

A scope is a method that customizes a given [[ActiveQuery]] object. Scope methods are defined
in the ActiveRecord classes. They can be invoked through the [[ActiveQuery]] object that is created
via [[find()]] or [[findBySql()]]. The following is an example:

~~~
class Customer extends \yii\db\ActiveRecord
{
	// ...

	/**
	 * @param ActiveQuery $query
	 */
Qiang Xue committed
414
	public static function active($query)
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
	{
		$query->andWhere('status = 1');
	}
}

$customers = Customer::find()->active()->all();
~~~

In the above, the `active()` method is defined in `Customer` while we are calling it
through `ActiveQuery` returned by `Customer::find()`.

Scopes can be parameterized. For example, we can define and use the following `olderThan` scope:

~~~
class Customer extends \yii\db\ActiveRecord
{
	// ...

	/**
	 * @param ActiveQuery $query
	 * @param integer $age
	 */
Qiang Xue committed
437
	public static function olderThan($query, $age = 30)
438
	{
Alexander Makarov committed
439
		$query->andWhere('age > :age', [':age' => $age]);
440 441 442 443 444 445 446 447
	}
}

$customers = Customer::find()->olderThan(50)->all();
~~~

The parameters should follow after the `$query` parameter when defining the scope method, and they
can take default values like shown above.
448 449 450 451

### Atomic operations and scenarios

TBD