7

I have Yii application and two tables with same structure tbl and tbl_history:

Now want to create model so it will select table by parameter I send when calling model. For example:

MyModel::model('tbl')->find();
//and
MyModel::model('tbl_history')->find();

Find related article with solution in Yii forum. Made same changes and finally got this in MyModel:

private $tableName = 'tbl'; // <=default value
private static $_models=array();
private $_md;

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->tableName = $tableName;

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

Now when I make:

echo MyModel::model('tbl_history')->tableName(); // Output: tbl_history

It returns right value, but:

MyModel::model('tbl_history')->find();

still returns value for tbl.

Added:

public function __construct($id=null,$scenario=null){
    var_dump($id);
    echo '<br/>';
    parent::__construct($scenario);
}

and got:

string(tbl_history)
string(tbl_history)
NULL

It means Yii makes call to model from other place but don't know from where and how to prevent it.

Also It makes 2 calls to model, is it too bad for performance?

5 Answers 5

5
+50

It looks like the CActiveRecord::getMetaData() method needs to be overridden to achieve what you are looking for.

<?php
class TestActiveRecord extends CActiveRecord
{
    private $tableName = 'tbl'; // <=default value
    private static $_models=array();
    private $_md;

    public function __construct($scenario='insert', $tableName = null)
    {

        if($this->tableName === 'tbl' && $tableName !== null)
            $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->tableName = $tableName;

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

            return $model;
        }
    }

    public function tableName()
    {
        return $this->tableName;
    }

    /**
     * Returns the meta-data for this AR
     * @return CActiveRecordMetaData the meta for this AR class.
     */
    public function getMetaData()
    {
        if($this->_md!==null)
            return $this->_md;
        else
            return $this->_md=static::model($this->tableName())->_md;
    }

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

}
3
  • Great, this works. it's not a big problem but now it returns data from tbl_history but table name write tbl. Is it possible to overwrite too?
    – Narek
    Commented May 13, 2013 at 7:12
  • 1
    @Narek I'ved added a __constructor method override that you can use to accomplish this. The main down side is that you need to specify the scenario for every instance you create. $model = new TestActiveRecort('insert', 'tbl_history'); Commented May 13, 2013 at 14:17
  • This works. I am looking for the same but i have acheived it in yii 1.1.14 by activerecord default method refreshMetaData() but in yii 1.1.13 it not worked. So You can check issue here stackoverflow.com/questions/29490565/… Commented Apr 8, 2015 at 7:09
2

Maybe it's easier to make MyModelHistory which extends MyModel and overrides only one method - tableName().

2
  • It's good for two tables, but I want to find global solution for multiple tables, even if I don't know table names.
    – Narek
    Commented May 8, 2013 at 13:52
  • @Narek I think there is two way one the way -urmaul- said which I think the best. one other is to modify AppModel to support that.which is not easy or maybe good.
    – Sina R.
    Commented May 11, 2013 at 9:01
2

I recommend implementing single table inheritance. In order to do this you will need to combine your tables with a flag or type column that states whether or not this is a history record. I've pasted a few links at the bottom so you can see how this is implemented in Yii and listed some of the benefits below.

Benefits:

  1. You won't need to duplicate code commonly used between the models

  2. Changes to this table will only need to be executed once.

  3. Changes to the parent model will only need to be made once.

  4. Code becomes generally more maintainable and readable.

  5. You seperate the code that belongs specifically to tbl and tbl_history

http://www.yiiframework.com/wiki/198/single-table-inheritance/ http://en.wikipedia.org/wiki/Single_Table_Inheritance

2

I created a solution for performing this exact action a couple of months ago. This is a completely dynamic solution, you just pass the table name like you are looking for to the model. That solution was originally designed to work with the same database structure across multiple databases, but it was trivial to adapt it to work in the same database. The documentation for that is here. I'd recommend reading over it as it has more details about CDynamicRecord

It's easy to adapt to work with multiple tables. You can download the adaptation as a gist from github.

Usage

1) Download the Gist and drop it into ext, save as CDynamicRecordSDB.php

2) Create Your model in Model, and setup up as follows:

Basically, you want to extend CDynamicRecord, and override your model() and tableName() so they are compliant with CDyanmicRecord.

<?php

Yii::import('ext.CDynamicRecordSDB');
class Test extends CDynamicRecordSDB
{
    public static function model($dbConnectionString = 0, $className=__CLASS__)
    {
        return parent::model($dbConnectionString, $className);
    }


    public function tableName()
    {
    return $this->dbConnectionString;
    }

     [... Do everything else after this ...]
}

3) Setup your model as you normally would.

Usage

The usage is identical to CActiveRecord, and you can perform all actions. No surprises. Just a couple examples below.

$data = Test::model('tbl')->findAll();
$data2 = new Test('tbl');
$data2->findAll();

foreach ($data as $row)
     print_r($row->attributes);

$data = Test::model('tbl_history')->findAll();
foreach ($data as $row)
     print_r($row->attributes);

Limitations

The only limitation with doing this is you have to modify how relations work. IF you plan on accessing a related model (Bar), and you have no intention on calling Bar by itself. Then Bar should extend CActiveRecord, and in Foo you can define normal relations. Yii magically carries over the CDbConnectionString across the instances for you.

OTHERWISE, if you intend to access models in the same database, but also want to retain the ability to call them by themselves, then Bar should extend CDynamicModel, and Foo should have a getter defined as follows.

public function getBar()
{
    return Bar::model($this->$dbConnectionString);
}
1

A small way but work for me for any number of table

public static $dynamic_table_name="main_table";

public static function setDynamicTable($param)
{
    self::$dynamic_table_name=self::$dynamic_table_name.$param;
}

/**
 * @return string the associated database table name
 */

public function tableName($param='')
{
    self::setDynamicTable($param);
    return self::$dynamic_table_name;
}


// to use it like 
 ModelName::model()->tableName('_one');
 ModelName::model()->tableName('_two');
 ModelName::model()->tableName('_three');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.