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
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();