Yii2 中的动态表名 [英] Dynamic table names in Yii2

查看:34
本文介绍了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;
}

更新:

好吧,我的错.如果您调用诸如 updateAllfind 等静态方法,则不会调用构造函数.并且不会设置 $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.

  1. 在使用静态数据库操作方法之前手动调用构造函数.
  2. 向模型添加一个静态 setter,如 public static function setTableName($tableName),并在每次成功登录时调用它.
  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.

这篇关于Yii2 中的动态表名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆