Dynamic table names in Yii2

后端 未结 3 1282
情书的邮戳
情书的邮戳 2021-01-14 13:46

I have a Yii2 Model that uses multiple tables with the same structure. The table names will change according to the user logged in and the table names are very unique and de

3条回答
  •  执念已碎
    2021-01-14 14:26

    This problem has been going on for a long time, but I just saw this problem and have some ideas, I hope to help later people.

    Setting the table name dynamically through the constructor is not friendly. we can bind the table name by setting a factory method, for example:

    class MyTableModel extends \yii\db\ActiveRecord {
    
        protected static $table;
    
        public static function useTable($table) {
            static::$table = $table;
    
            return new static();
        }
    
        public static function tableName() {
            return static::$table;
        }
    }
    

    When used, bind the table name through the useTable, for example:

    // find
    MyTableModel::useTable('tableName1')::find()->where(...)->all(); // use tableName1
    MyTableModel::useTable('tableName1')::findAll(); // use tableName1
    MyTableModel::useTable('tableName1')::updateAll(); // use tableName1
    
    MyTableModel::useTable('tableName2')::findAll(); // use tableName2
    
    // create 
    $table = MyTableModel::useTable('tableName2');
    $table->attributes = $attributes;
    $table->save()
    

    Use the useTable method to achieve a fully bound target.

    Note that this is not done with a closure, but instead sets the value of the MyTableModel::$table static variable. So calling useTable multiple times will use the last set value

提交回复
热议问题