active-record.md 17.1 KB
Newer Older
Alexander Makarov committed
1 2 3 4 5
Active Record
=============

ActiveRecord implements the [Active Record design pattern](http://en.wikipedia.org/wiki/Active_record).
The idea is that an ActiveRecord object is associated with a row in a database table so object properties are mapped
Qiang Xue committed
6
to columns of the corresponding database row. For example, a `Customer` object is associated with a row in the
Alexander Makarov committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
`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 to achieve the same goals. For example, calling [[save()]] would insert or update a row
in the underlying table:

```php
$customer = new Customer();
$customer->name = 'Qiang';
$customer->save();
```


Declaring ActiveRecord Classes
------------------------------

To declare an ActiveRecord class you need to extend [[\yii\db\ActiveRecord]] and
Qiang Xue committed
24
implement the `tableName` method like the following:
Alexander Makarov committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41

```php
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
----------------------

Qiang Xue committed
42 43 44 45
ActiveRecord relies on a [[Connection|DB connection]] to perform the underlying DB operations.
By default, it assumes that there is an application component named `db` which gives the needed
[[Connection]] instance. Usually this component is configured via application configuration
like the following:
Alexander Makarov committed
46 47 48 49 50 51 52 53 54

```php
return array(
	'components' => array(
		'db' => array(
			'class' => 'yii\db\Connection',
			'dsn' => 'mysql:host=localhost;dbname=testdb',
			'username' => 'demo',
			'password' => 'demo',
Qiang Xue committed
55
			// turn on schema caching to improve performance in production mode
Alexander Makarov committed
56 57 58 59 60 61
			// 'schemaCacheDuration' => 3600,
		),
	),
);
```

Qiang Xue committed
62 63 64
Please read the [Database basics](database-basics.md) section to learn more on how to configure
and use database connections.

Alexander Makarov committed
65 66 67 68

Getting Data from Database
--------------------------

Qiang Xue committed
69
There are two ActiveRecord methods for getting data from database:
Alexander Makarov committed
70 71 72 73

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

Qiang Xue committed
74 75
They both return an [[ActiveQuery]] instance. Coupled with various query methods provided
by [[ActiveQuery]], ActiveRecord supports very flexible and powerful data retrieval approaches.
Alexander Makarov committed
76 77 78 79 80 81 82 83 84 85 86

The followings are some examples,

```php
// to retrieve all *active* customers and order them by their ID:
$customers = Customer::find()
	->where(array('status' => $active))
	->orderBy('id')
	->all();

// to return a single customer whose ID is 1:
Qiang Xue committed
87 88 89
$customer = Customer::find(1);

// the above code is equivalent to the following:
Alexander Makarov committed
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
$customer = Customer::find()
	->where(array('id' => 1))
	->one();

// 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:
$count = Customer::find()
	->where(array('status' => $active))
	->count();

// 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
---------------------

ActiveRecord maps each column of the corresponding database table row to an *attribute* in the ActiveRecord
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:

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

We can get all column values through the [[attributes]] property:

```php
$values = $customer->attributes;
```


Qiang Xue committed
136 137
Saving Data to Database
-----------------------
Alexander Makarov committed
138

Qiang Xue committed
139
ActiveRecord provides the following methods to insert, update and delete data in the database:
Alexander Makarov committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

- [[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:

```php
// 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();
166
// Note that model attributes will be validated first and
Alexander Makarov committed
167
// model will not be saved unless it's valid.
Alexander Makarov committed
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

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

// to increment the age of all customers by 1
Customer::updateAllCounters(array('age' => 1));
```


Getting Relational Data
-----------------------

Using ActiveRecord you can expose relationships as properties. For example, with an appropriate declaration,
`$customer->orders` can return an array of `Order` objects which represent the orders placed by the specified customer.

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

```php
class Customer extends \yii\db\ActiveRecord
{
	public function getOrders()
	{
		return $this->hasMany('Order', array('customer_id' => 'id'));
	}
}

class Order extends \yii\db\ActiveRecord
{
	public function getCustomer()
	{
		return $this->hasOne('Customer', array('id' => 'customer_id'));
	}
}
```

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.
Both methods take two parameters:

Qiang Xue committed
210 211 212
- `$class`: the name of the class of the related model(s). If specified without
  a namespace, the namespace of the related model class will be taken from the declaring class.
- `$link`: the association between columns from the two tables. This should be given as an array.
Alexander Makarov committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
  The keys of the array are the names of the columns from the table associated with `$class`,
  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.

After declaring relationships getting relational data is as easy as accessing
a component property that is defined by the getter method:

```php
// the orders of a customer
$customer = Customer::find($id);
$orders = $customer->orders;  // $orders is an array of Order objects

// the customer of the first order
$customer2 = $orders[0]->customer;  // $customer == $customer2
```

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:

```php
class Customer extends \yii\db\ActiveRecord
{
	public function getBigOrders($threshold = 100)
	{
		return $this->hasMany('Order', array('customer_id' => 'id'))
			->where('subtotal > :threshold', array(':threshold' => $threshold))
			->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:

```php
class Order extends \yii\db\ActiveRecord
{
	public function getItems()
	{
		return $this->hasMany('Item', array('id' => 'item_id'))
			->viaTable('tbl_order_item', array('order_id' => 'id'));
	}
}
```

[[ActiveRelation::via()]] method is similar to [[ActiveRelation::viaTable()]] except that
Qiang Xue committed
266 267
the first parameter of [[ActiveRelation::via()]] takes a relation name declared in the ActiveRecord class
instead of the pivot table name. For example, the above `items` relation can be equivalently declared as follows:
Alexander Makarov committed
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317

```php
class Order extends \yii\db\ActiveRecord
{
	public function getOrderItems()
	{
		return $this->hasMany('OrderItem', array('order_id' => 'id'));
	}

	public function getItems()
	{
		return $this->hasMany('Item', array('id' => 'item_id'))
			->via('orderItems');
	}
}
```


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,

```php
// 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;
```


Lazy loading is very convenient to use. However, it may suffer from performance
issue in the following scenario:

```php
// 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
the database? 101! The first SQL query brings back 100 customers. Then for each customer, a SQL query
is performed to bring back the customer's orders.

Qiang Xue committed
318
To solve the above performance problem, you can use the so-called *eager loading* approach by calling [[ActiveQuery::with()]]:
Alexander Makarov committed
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471

```php
// 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...
}
```

As you can see, only two SQL queries are needed for the same task.


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,

```php
$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
$customers = Customer::find()->limit(100)->with(array(
	'orders' => function($query) {
		$query->andWhere('subtotal>100');
	},
))->all();
```


Working with Relationships
--------------------------

ActiveRecord provides the following two methods for establishing and breaking a
relationship between two ActiveRecord objects:

- [[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:

```php
$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
-------------------------

ActiveRecord inherits data validation and data input features from [[\yii\base\Model]]. Data validation is called
automatically when `save()` is performed and is canceling saving in case attributes aren't valid.

For more details refer to [Model](model.md) section of the guide.


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
2. [[init()]]: will trigger an [[EVENT_INIT]] event

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

1. constructor
2. [[init()]]: will trigger an [[EVENT_INIT]] event
3. [[afterFind()]]: will trigger an [[EVENT_AFTER_FIND]] event

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

1. [[beforeValidate()]]: will trigger an [[EVENT_BEFORE_VALIDATE]] event
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

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

1. [[beforeDelete()]]: will trigger an [[EVENT_BEFORE_DELETE]] event
2. perform the actual data deletion
3. [[afterDelete()]]: will trigger an [[EVENT_AFTER_DELETE]] event


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:

```php
class Customer extends \yii\db\ActiveRecord
{
	// ...

	/**
	 * @param ActiveQuery $query
	 */
	public static function active($query)
	{
		$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:

```php
class Customer extends \yii\db\ActiveRecord
{
	// ...

	/**
	 * @param ActiveQuery $query
	 * @param integer $age
	 */
	public static function olderThan($query, $age = 30)
	{
		$query->andWhere('age > :age', array(':age' => $age));
	}
}

$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.

Atomic operations and scenarios
-------------------------------

472 473 474 475
TODO: FIXME: WIP, TBD, https://github.com/yiisoft/yii2/issues/226

Imagine situation where you have to save something related to the main model in [[beforeSave()]],
[[afterSave()]], [[beforeDelete()]] and/or [[afterDelete()]] life cycle methods. Developer may come
Qiang Xue committed
476
to the solution of overriding ActiveRecord [[save()]] method with database transaction wrapping or
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
even using transaction in controller action, which is strictly speaking doesn't seems to be a good
practice (recall skinny-controller fat-model fundamental rule).

Here these ways are (**DO NOT** use them unless you're sure what are you actually doing). Models:

```php
class Feature extends \yii\db\ActiveRecord
{
	// ...

	public function getProduct()
	{
		return $this->hasOne('Product', array('product_id' => 'id'));
	}
}

class Product extends \yii\db\ActiveRecord
{
	// ...

	public function getFeatures()
	{
		return $this->hasMany('Feature', array('id' => 'product_id'));
	}
}
```

Overriding [[save()]] method:

```php

class ProductController extends \yii\web\Controller
{
	public function actionCreate()
	{
		// FIXME: TODO: WIP, TBD
	}
}
```

Using transactions within controller layer:

```php
class ProductController extends \yii\web\Controller
{
	public function actionCreate()
	{
		// FIXME: TODO: WIP, TBD
	}
}
```

Instead of using these fragile methods you should consider using atomic scenarios and operations feature.

```php
class Feature extends \yii\db\ActiveRecord
{
	// ...

	public function getProduct()
	{
		return $this->hasOne('Product', array('product_id' => 'id'));
	}

	public function scenarios()
	{
		return array(
			'userCreates' => array(
				'attributes' => array('name', 'value'),
				'atomic' => array(self::OP_INSERT),
			),
		);
	}
}

class Product extends \yii\db\ActiveRecord
{
	// ...

	public function getFeatures()
	{
		return $this->hasMany('Feature', array('id' => 'product_id'));
	}

	public function scenarios()
	{
		return array(
			'userCreates' => array(
				'attributes' => array('title', 'price'),
				'atomic' => array(self::OP_INSERT),
			),
		);
	}

	public function afterValidate()
	{
		parent::afterValidate();
		// FIXME: TODO: WIP, TBD
	}

	public function afterSave($insert)
	{
		parent::afterSave();
		if ($this->getScenario() === 'userCreates') {
			// FIXME: TODO: WIP, TBD
		}
	}
}
```

Controller is very thin and neat:

```php
class ProductController extends \yii\web\Controller
{
	public function actionCreate()
	{
		// FIXME: TODO: WIP, TBD
	}
}
```
Alexander Makarov committed
598 599 600 601 602

See also
--------

- [Model](model.md)
603
- [[\yii\db\ActiveRecord]]