One question I hear many people ask around the Yii forum is how to use table prefixes with ActiveRecord. I believe the best way to solve this problem is to extend CActiveRecord::tableName(). Now you can either extend this method in every active record class you would like to use a prefix manually, or you can create a new active record class that supports this functionality, and then have all your other active record classes extend this new class. This is what I mean:

Normally your active record classes would have the following inheritance:[...] -> CModel -> CActiveRecord -> YourARModels

Instead, you may create a new active record class with custom functionality that you want all your active record classes to have, such as the table prefix functionality. So the inheritance would look like this:[...] -> CModel -> CActiveRecord -> ActiveRecord -> YourARModels

To do this simply create a ActiveRecord class and save it in a directory that is set to auto-load classes on demand (probably /protected/models or /protected/components should work). It could look something like this:

Then you would have all your active record classes simply extend ActiveRecord instead of CActiveRecord. If you do not want a single active record to have a prefix, you can set the $tablePrefix attribute to an empty string in that active record.

You may of course add other useful functionalities that you would like your active record models to share in this class.

5 Comments

I can see how this might seem like a hassle to some people, but the truth is, in most apps you would probably need to extend CActiveRecord anyways. Also this is more flexible, such as you have the ability to change the case (lower(), upper(), ucfirst()), and other things you might need.