Dynamic table name in model

Hello!

I tried to search, but have not succeeded in this…

The problem is as follows: I have several components, that are set by user in backend, so I don’t know in advance, how many tables in db there will be and how many models the application will need. Each table has a predefined schema (e.g. id, name, data), and table names are like “data{$component_id}”.

What is the best way for managing these tables? I tried to modify model’s tableName() method, adding setter for this and constructor for class, but… I also tried to search for dynamic migrations and dynamic models, but no luck there too…

I will be grateful for any ideas.

My non-working samples are below:

Extract from model class code:




    protected static $table;


    public function __construct($table)

    {

        self::$table = $table;

    }


    public static function tableName()

    {

        return self::$table;

    }


    public static function setTableName($table)

    {

        self::$table = $table;

    }



Trying to call it:




    public function actionIndex()

    {

        ContentData::setTableName('_data_test2');

        $model=ContentData::find(1);

        die(var_dump($model));

    }



Difficult to solve…

Is it not possible to work together with user? So much assumptions can be avoided if you have a joint plan.

Actually, this user is not a particular person. I want to implement some kind of editing that is used in, for example, in 1C-Bitrix or NetCat. The idea is that if you have news - you create data block called "news", define several fields, some code to work with and go on. Later you need to implement a list of projects - you create data block called "projects" … etc.

I mean, the idea is exactly in creating as many tables/components, as user needs

Will this be possible using gii? This will create the code as per yii standards.

http://www.yiiframework.com/doc-2.0/ext-gii-index.html

One other suggestion is to avoid using active record in your particular case.




class Yourclass {

	private $_table;

	

	public function settable($tableFullName) {

		$this->$_table=$tableFullName;

	}

	

	// Your functions with plain sql code follows


}



Is it possible to run gii programmaticaly? I.e. from controller action? Or the only way is to run exec(’./yii …’)?

Yes, avoiding AR is the solution, which I have meant to use if no "beautiful" solution is available…