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:
// turn on schema caching to improve performance
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.
$post->content='content for the sample post';
3. Reading Record
To read data in a database table, we call one of the find methods as follows.
// find the first row satisfying the specified condition
// find the row with the specified primary key
// find the row with the specified attribute values
// find the first row using the specified SQL statement
4. Updating Record
After an AR instance is populated with column values, we can change them and save them back to the database table.
$post->title='new post title';
$post->save(); // save the change to database
5. Deleting Record
We can also delete a row of data if an AR instance has been populated with this row.
$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10
$post->delete(); // delete the row from the database table
Note, after deletion, the AR instance remains unchanged, but the corresponding row in the database table is already gone.
The following class-level methods are provided to delete rows without the need of loading them first:
// delete the rows matching the specified condition
// delete the rows matching the specified condition and primary key(s)
6. Data Validation
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: