Yii Framework Forum: Model with dynamic table name - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Model with dynamic table name Rate Topic: -----

#1 User is offline   LukaszFokin 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 32
  • Joined: 14-June 11

Posted 16 April 2012 - 10:09 AM

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
0

#2 User is offline   Haensel 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 444
  • Joined: 14-January 11
  • Location:Vienna (Austria)

Posted 16 April 2012 - 02:38 PM

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.
0

#3 User is offline   Taro Uma 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 30-May 13

Posted 30 May 2013 - 04:00 PM

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?
0

#4 User is offline   Taro Uma 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 30-May 13

Posted 07 June 2013 - 03:09 PM

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;
                                }
	}

0

#5 User is offline   Tsunami 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 150
  • Joined: 16-February 12

Posted 07 June 2013 - 03:54 PM

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.
0

#6 User is offline   Taufik 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 10
  • Joined: 07-February 11
  • Location:Indonesia

Posted 11 February 2014 - 06:36 AM

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

#7 User is offline   kokila 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 4
  • Joined: 23-June 14

Posted 22 July 2014 - 09:04 AM

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 $tableName ;
private static $_models = array();
private $_md;

public function __construct($tableName = null, $scenario = 'insert') {
if ($tableName === null || $tableName === '') {
/* set the tableName here if you want */
/* following 4 lines set default table name of my application */
$criteria = new CDbCriteria();
$criteria->select = 'MAX(Year) as Year';
$tableName = AcademicCalendar::model()->find($criteria)->Year;
$this->tableName = 'lecture' . $tableName;
}
$this->tableName =$tableName;
parent::__construct($scenario);


}

public static function model($tableName = false, $className = __CLASS__) {

if ($tableName === null)
$className = null;
// this string will save internal CActiveRecord functionality
if (!$tableName)
return parent::model($className);
if (isset(self::$_models[$tableName . $className]))
return self::$_models[$tableName . $className];
else {
$model = self::$_models[$tableName . $className] = new $className(null);
//$model = parent::model();
$model->tableName = $tableName;

$model->_md = new CActiveRecordMetaData($model);
$model->attachBehaviors($model->behaviors());

return $model;
}
}

public function tableName() {
return $this->tableName;
}
public function getMetaData() {
if ($this->_md === null){

$this->_md = new CActiveRecordMetaData($this);
}return $this->_md;
}

public function refreshMetaData() {
$finder = static::model($this->tableName());
$finder->_md = new CActiveRecordMetaData($finder);
if ($this !== $finder)
$this->_md = $finder->_md;
}

Attached File(s)


0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users