Table prefixes

April 9th, 2009

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:

class ActiveRecord extends CActiveRecord
	public $tablePrefix = 'myPrefix_';
	public function tableName()
		return $this->tablePrefix.parent::tableName();

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.

Share and Enjoy:
  • Digg
  • Facebook
  • Google Bookmarks
  • Technorati
  • Reddit
  • RSS
  • Twitter

Categories: Yii

Tags: , Leave a comment

Comments Feed5 Comments

  1. ryan

    This deserves a ticket :)
    I have already submitted an enhancement ticket #242

  2. Jonah

    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.

  3. JamesD

    Thanks for the useful info. It’s so interesting

  4. Ian Hunter

    My tableName method doesn’t seem to be getting called at all — I wonder if something has changed in the latest version?

  5. Ian Hunter

    Wait — I take that back. I had specified my tablename elsewhere. My bad. :)

Leave a comment

five × = 35

Feed / Table prefixes