Dynamic table names in Yii2

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

    Since tableName is a static method (exactly what the error message says) you don't have access to non-static properties. (you can't use $this keyword)

    So you'd have to declare a static property:

    protected static $table;
    
    public function __construct($table)
    {
        self::$table = $table;
    }
    
    public static function tableName()
    {
        return self::$table;
    }
    
    /* UPDATE */
    public static function setTableName($table)
    {
        self::$table = $table;
    }
    

    UPDATE:

    Ok my fault. The constructor will not get called if you call a static method like updateAll, find etc. And $table will not get set. So you have different options.

    1. Manually call the constructor before using the static db manipulation methods.
    2. Add a static setter to the model like public static function setTableName($tableName) and call it on every successful login.

提交回复
热议问题