Chinmay Waghmare
Chinmay Waghmare

Reputation: 5456

Yii2 How to create models dynamically and specify relationship among them?

I am creating tables on the fly. If I created the tables Schools and Classes. How can I create the models for them and specify relationships among them.

I searched but did not get anything on this topic. Any help would be appreciated. Thank you.

Upvotes: 2

Views: 1280

Answers (1)

Pavel Bariev
Pavel Bariev

Reputation: 2626

The only way I can figure out is to use "global variables" for tables - e.g. in Yii::$app->params['ar_tables'] and redefine them dynamically:

In config:

[
    ....
    'params' => [
         'ar_tables' => [
             'Parent' => 'parent',
             'Child' => 'table2' 
         ]
    ]
    ....
]

Parent class:

class Parent extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return Yii::$app->params['ar_tables']['Parent'];
    }


    public function getChildren
    {
        return self::hasMany(Child::className(), ['parent_id' => 'id']);
    }
}

Child class:

class Child extends \yii\db\ActiveRecord
{

    public static function tableName()
    {
        return Yii::$app->params['ar_tables']['Child'];
    }


    public function getParent
    {
        return self::hasOne(Parent::className(), ['id' => 'parent_id']);
    }   
}

After that you can dynamically change Yii::$app->params['ar_tables'] values for getting what you want. I have already tried this. And didn't like :)

Upvotes: 1

Related Questions