Yii2中的动态表名称 [英] Dynamic table names in Yii2
问题描述
我有一个Yii2模型,该模型使用具有相同结构的多个表.表名将根据登录的用户而改变,并且表名非常唯一并且取决于用户名.我如何动态地将此表名分配给模型?到目前为止,我已经做到了.
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 depends on the username .How will i assign this table name to the model dynamically?I have done this so far.
在我的模型中:
protected $table;
public function __construct($table)
{
$this->table='custom_risk_assignment_table';//logic to obtain the table name goes here
}
public static function tableName()
{
return $this->table;
}
但是这样做会导致错误Using $this when not in object context
,因为function tableName()
是static
函数.
But by doing so results in error Using $this when not in object context
since function tableName()
is a static
function.
那我该怎么办?任何帮助表示赞赏.谢谢!!
How can i do it then?Any help appreciated.Thanks in advance!
详细图片
说我有一个来自ABC公司的用户.我的应用程序中有很多流程,例如PQR就是其中之一.如果ABC公司的用户登录并选择进程PQR,我需要在我的数据库中创建一个表ABC_PQR(如果不存在)或加载该表(如果已经创建).我需要将此表名称添加到我的模型中.同样,用户和许多进程可能在那里.什么是管理数据库的最佳方法.
Say i have a user from the company ABC. I have so many processes in my application,say PQR is one of them. If user from the company ABC logins and choose the process PQR,i need to create a table ABC_PQR in my database if not exists or load the table if it is already created. I need this table name into my model. Similarly may users and many processes are there.What will be the best approach to manage the database.
推荐答案
由于tableName
是静态方法(错误消息所确切说明的),因此您无权访问非静态属性. (您不能使用$this
关键字)
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;
}
更新:
好吧,我的错.如果您调用诸如updateAll
,find
等静态方法,则不会调用构造函数.并且$table
也不会被设置.因此,您有不同的选择.
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.
- 在使用静态数据库操作方法之前,手动调用构造函数.
- 向模型添加静态设置器,例如
public static function setTableName($tableName)
,并在每次成功登录时调用它.
- Manually call the constructor before using the static db manipulation methods.
- Add a static setter to the model like
public static function setTableName($tableName)
and call it on every successful login.
这篇关于Yii2中的动态表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!