Yii 1.1: dynamic-active-record

CActiveRecord implementation that allows specifying DB table name instead of creating a class for each table.

This class allows accessing DB tables in an AR-like fashion, without the need to create a class for each table.


Copy class to your project (eg to protected/components). Create a new instance by specifying table name:

$userModel = DynamicActiveRecord::forTable('user');

And then use it like any other AR class:

//list existing users
foreach ($userModel->findAll() as $user)
    echo $user->id . ': ' . $user->name . '<br>';
//add new user
$userModel->name = 'Pavle Predic';



Total 4 comments

#18148 report it
I Made Purnama Yasa at 2014/09/16 10:58am
Automatic Rules

I create code for dynamic rules

this automatic rules from table schema, and check in field is allow null or not

         * @return array validation rules for model attributes.
        public function rules()
                // NOTE: you should only define rules for those attributes that
                // will receive user inputs.
                $columns = Yii::app()->db->schema->tables[$this->_tableName]->columns;
                foreach ($columns as $column => $schema) {
                        if (!$schema->allowNull) {
                                $tmp_columns[] = $column;
                $col = implode(',',$tmp_columns);
                return array(
#9983 report it
yiqing95 at 2012/09/26 11:19pm
@ I'm not entirely sure what this class is good for. good for manymany relation delete

in many many relations . if our database don't support the cascade deletion , we will have to delete the connection manually by ourselves . the better way is that generate a ActiveRecord for the bridge table . then

// afterDelete of the models which connected to each others , both side is ok 
ConnectionTable::model()->deleteAllByAttributes(array('model_id' => $model->id));

but it seems the ConnectionTable is only useful in such scenario (or you manually construct the connection)! so dynamicActiveRecord come here !

#9388 report it
pavlepredic at 2012/08/08 04:27am

Yes, you do lose a lot of AR functionality. But the idea behind this class is that sometimes you simply need to perform a basic read/write on a table and it doesn't warrant creating a whole new class for it. If you need validation, relations etc. then use the good old way. To be honest, I'm not entirely sure what this class is good for. I wrote it simply because someone on Yii forum was asking if this was possible in Yii and I guess this proves that: Yes It Is ;)

#9377 report it
Maciej Liżewski at 2012/08/07 12:24pm
nice, but what about "rules", "relations", etc?

you cannot use 'massive assignements', validation, relations, and stuff like that... They are configured in separate functions of each model definition, and this is it's all about with ActiveRecord...

Leave a comment

Please to leave your comment.

Create extension
No downloadable files yet