Dynamic table names in Yii2

后端 未结 3 1281
情书的邮戳
情书的邮戳 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:22

    One way to get out of this situation without hacks is to not vary the return value of tableName but instead use different classes for the different tables. Those classes would differ only in the implementation of tableName:

    abstract class Foo extends ActiveRecord
    {
        // your existing code goes here
    
        abstract function tableName();
    }
    
    class FooOne extends Foo
    {
        function tableName() { return 'table1'; }
    }
    
    class FooTwo extends Foo
    {
        function tableName() { return 'table2'; }
    }
    

    Then, at some appropriate place in your app you would decide which table you want to use and remember what the model for that table is. Something like:

    if ($username == "anne") {
        $fooModel = new FooOne();
    }
    else if ($username == "bob") {
        $fooModel = new FooTwo();
    }
    

    After this you can simply use $fooModel as the call target and the query will affect the appropriate table automatically. For example:

    $foos = $fooModel::findAll();
    

提交回复
热议问题