Model with dynamic table name

Good morning, I have a model where there is not a specific table set. For the system generates various tables the same but with different terms. And not having to create multiple models, I’m trying to create a model and just change the name of the table creating a method __ construct. See below:

This is my model …




<?php


class Termos extends CActiveRecord

{


        public $tabela;

        

        

        public function __construct($tabela){

                $this->tabela = $tabela;                                

        }

        

        

        /**

         * Returns the static model of the specified AR class.

         * @param string $className active record class name.

         * @return Termos the static model class

         */

        public static function model($className=__CLASS__)

        {

                return parent::model($className);

        }


        /**

         * @return string the associated database table name

         */

        public function tableName()

        {

                return $this->tabela;

        }


        /**

         * @return array validation rules for model attributes.

         */

        public function rules()

        {

                // NOTE: you should only define rules for those attributes that

                // will receive user inputs.

                return array(

                        array('rotulo_original, rotulo', 'required'),

                        array('rotulo_original, rotulo', 'length', 'max'=>350),

                        // The following rule is used by search().

                        // Please remove those attributes that should not be searched.

                        array('id_termo, rotulo_original, rotulo', 'safe', 'on'=>'search'),

                );

        }


        /**

         * @return array relational rules.

         */

        public function relations()

        {

                // NOTE: you may need to adjust the relation name and the related

                // class name for the relations automatically generated below.

                return array(

                );

        }


        /**

         * @return array customized attribute labels (name=>label)

         */

        public function attributeLabels()

        {

                return array(

                        'id_termo' => 'Id Termo',

                        'rotulo_original' => 'Rotulo Original',

                        'rotulo' => 'Rotulo',

                );

        }


        /**

         * Retrieves a list of models based on the current search/filter conditions.

         * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

         */

        public function search()

        {

        /**

 * This is the model class for table "lingua_portugues".

 *

 * The followings are the available columns in table 'lingua_portugues':

 * @property integer $id_termo

 * @property string $rotulo_original

 * @property string $rotulo

 */     // Warning: Please modify the following code to remove attributes that

                // should not be searched.


                $criteria=new CDbCriteria;

                $criteria->addCondition("rotulo LIKE :rotulo OR rotulo_original LIKE :rotulo");

                $criteria->params = array(':rotulo'=>"%".$this->rotulo."%");


                return new CActiveDataProvider($this, array(

                        'criteria'=>$criteria,

                ));

        }

        

}



And that’s the call model in controller…




$model=new Termos('lingua_portugues');



But when I call the $model->search() get this error: The table "" active record class "Terms", could not be found in the database.

In other words, is not passing the table name, the name of TableA is going right, but do not know what happens when the method when it comes tableName(), it does not get the right value.

Can anyone help me?

Thank you in advance

As far as I know CActiveRecord this is not possible with the current implementation. First, you override the constructor the wrong way. Take a look at the parent implementation CActiveRecord __construct() The problem is that this method calls getMetaData() which itself checks the table to get the schema (column names and datatypes). So you need the tableName() at the moment the model is instantiated. If you just add a constructor like you did you won’t create any metadata object and thus won’t have any table info which is essential for the queries.

Is there no way to pass a table name to the model? I really need to do this, and I have one method working simply when a user is logged in, to append a variable from the user




public function tableName()

	{

		return 'table_'.Yii::app()->user->table_id;

	}



Works a charm for when that table_id is available.

But I have a mobile app that does not have the user available. It has the table_id stored in the app, but does not create a session. So either I have to create a new Table_x.php model file for every single table or find a way to pass the table name to a single controller. Is not possible?

I have update, for my mobile controller which would not hold a session, I was able to set a param, which it could hold long enough to send to the model. (I think the problem is that the mobile app calls the controller via ajax




public function tableName()

	{

                                if(isset(Yii::app()->params['table_name'])){

                                        return 'table_'.Yii::app()->params['table_name'];

                                }else{

                                        return 'table_'.Yii::app()->user->table_name;

                                }

	}



What are these tables for? Translations or something? I think you are trying to find a solution to a problem that does not exist. If you have multiple tables with the same structure, your database design is wrong.

this database design not wrong, because I need this situation on my table partitioning (I use Postgresql)… how to do this?

I have implement the model for a similar occasion. See if my code will help you,

check my code :

/* start_of_dynamic_tables_code */

private &#036;tableName ;


private static &#036;_models = array();


private &#036;_md;





public function __construct(&#036;tableName = null, &#036;scenario = 'insert') {


    if (&#036;tableName === null || &#036;tableName === '') {


        /* set the tableName here if you want  */


        /* following 4 lines set default table name of my application */


        &#036;criteria = new CDbCriteria();


        &#036;criteria-&gt;select = 'MAX(Year) as Year';


        &#036;tableName = AcademicCalendar::model()-&gt;find(&#036;criteria)-&gt;Year;


        &#036;this-&gt;tableName = 'lecture' . &#036;tableName;


    }


    &#036;this-&gt;tableName =&#036;tableName;


    parent::__construct(&#036;scenario);


    


    


}





public static function model(&#036;tableName = false, &#036;className = __CLASS__) {


    


    if (&#036;tableName === null)


        &#036;className = null;


    // this string will save internal CActiveRecord functionality


    if (&#33;&#036;tableName)


        return parent::model(&#036;className);


    if (isset(self::&#036;_models[&#036;tableName . &#036;className]))


        return self::&#036;_models[&#036;tableName . &#036;className];


    else {


        &#036;model = self::&#036;_models[&#036;tableName . &#036;className] = new &#036;className(null);


        //&#036;model = parent::model();


        &#036;model-&gt;tableName = &#036;tableName;





        &#036;model-&gt;_md = new CActiveRecordMetaData(&#036;model);


        &#036;model-&gt;attachBehaviors(&#036;model-&gt;behaviors());





        return &#036;model;


    }


}





public function tableName() {


    return &#036;this-&gt;tableName;


}


public function getMetaData() {


    if (&#036;this-&gt;_md === null){


        


        &#036;this-&gt;_md = new CActiveRecordMetaData(&#036;this);


    }return &#036;this-&gt;_md;


}





public function refreshMetaData() {


    &#036;finder = static::model(&#036;this-&gt;tableName());


    &#036;finder-&gt;_md = new CActiveRecordMetaData(&#036;finder);


    if (&#036;this &#33;== &#036;finder)


        &#036;this-&gt;_md = &#036;finder-&gt;_md;


}