Learning Yii Relational Active Record

One thing I impress of YII is there Active Record feature. Instead of declaring the sql command to query the data of two or more tables. In YII we can just create relation function in the model class to join the tables by assigning the foreign keys.

Yii Relational Active Record Approaches

In Yii there are two approaches mainly the lazy loading approach and the eager loading approach. Both approaches have been documented on Yii relational active record tutorial. But if you are lazy to read, this is how each approach is being use. Lazy loading approach is use when you are dealing with 1 record and eager loading approach comes in handy when there are more than 1 records you wish to access. This is made in this way to reduce the number of join which lead to inefficiency according to Yii document page.

1. Establishing DB Connection

The following application configuration shows an example:

1

2

3

4

5

6

7

8

9

10

returnarray(

'components'=>array(

'db'=>array(

'class'=>'system.db.CDbConnection',

'connectionString'=>'sqlite:path/to/dbfile',

// turn on schema caching to improve performance

// 'schemaCachingDuration'=>3600,

),

),

);

2.- Creating Record

To insert a new row into a database table, we create a new instance of the corresponding AR class, set its properties associated with the table columns, and call the save() method to finish the insertion.

1

2

3

4

5

$post=newPost;

$post->title='sample post';

$post->content='content for the sample post';

$post->create_time=time();

$post->save();

3. Reading Record

To read data in a database table, we call one of the find methods as follows.

AR performs data validation automatically when save() is being invoked. The validation is based on the rules specified in the rules() method of the AR class. For more details about how to specify validation rules, refer to the Declaring Validation Rules section. Below is the typical workflow needed by saving a record: