Yii2 – What you need to know – Part III (Active Record)

Active Record

In this installment of the series where we are exploring the Yii2 framework, we will look in detail at the Active Record and database aspects of this powerful framework. We feel that this is one of the strongest sections of Yii2 in terms of both improvements as well as addition of new features.

Database Support in the new Active Record class

Among the big news in Yii2 Active Record is the support for numerous new backends including NoSQL based ones. These backends include elasticsearch, redis, Sphinx search as well as mongodb. This is great news as we can switch backends without touching our code provided all our code uses Active Records for DB interaction.

Selecting Data in Yii2 using Active Record

The first major change you will come across here is the demise of model() call. All find methods now stem from either find() or findBySql(). So (using the blog example), Post::model()->findAll() is replaced by Post::find()->all(). This introduces unprecedented flexibility in selecting records from the db and is also very intuitive to use once we get used to it. This will become more clear when you go through the following code from the Definitive Guide on how to select data from db using the new Active Record implementation:

Also, some shortcut, functions are now available to replace the findByPk() and find() methods from Yii 1.1.

Relations

Gone are the relations(), now replaced by getters that return ActiveQuery objects.

The relation can thus still be used via $game->players, but now you can customize query conditions on the fly, e.g.:

Miscellaneous

There are many more subtle changes that will make you fall in love with this framework all over again. You may want to use arrays to hold the data retrieved from database to save memory. This can be done by calling asArray().

You may use batch query to keep your memory usage under a limit when querying a large amount of data from database. You may use the same technique in Active Record.

In addition, Yii2 now supports nested transactions so that you do not have to worry about whether transactions have already been declared within the current call stack.

Conclusion

This is by no means an exhaustive listing of all the changes and improvements that can be found in the Active Record pattern implementation in Yii2. We found the changes to be quite intuitive and flexible. Let us know what you think. For a good Angular2 + Yii2 project structure, you can visit the linked page.

Navigate to other parts of the series:

Part I, Part II, Part IV and Part V

Note: Post was moved here from my old blog…

Leave a Reply

Your email address will not be published. Required fields are marked *