繁体   English   中英

如何在 Yii2 中创建 Model 并每月增加表

[英]How to create a Model in Yii2 with increase of table every month

我有一个考勤系统,每个月都会增加一张桌子。 Like for the month of April 2020 the name of table is att202004, May 2020 the name of table is att202005 and etc. As you know the model name and naming file in Yii2 is static and I have to create new model every month. 如何创建一个处理所有月份出勤的 model。 TQ

如果您只需要为有限数量的表创建模型,例如仅针对当前月份,您可以使用事实,即表名是在 static 方法中定义的,因此您可以拥有动态表名。

class CurrentMonth extends yii\db\ActiveRecord
{
    public static function tableName()
    {
        return 'att' . date('Ym');
    }

    //... other definitions
}

如果您需要为每个现有表创建 model,您可以使用自动加载器动态创建类。

在 autoload.php 中实现并注册您的自动加载器。 在这个例子中,我将假设表被命名为att202005并且创建的模型将是\app\dynamicModels\Att202005

class DynamicModelFactory
{
    protected static function classBasename($class)
    {
        $split = explode('\\', $class);
        return end($split);
    }

    public static function autoload($class)
    {
        if (strpos($class, 'app\\dynamicModels') !== 0) {
            //skip if the class is not in app\dynamicModels namespace
            return;
        }

        $className = static::classBasename($class);
        //get table name from class name by converting the first letter to lower case
        $tableName = lcfirst($className);

        $template = static::template();
        $template = str_replace(
            ['{className}', '{tableName}'],
            [$className, $tableName],
            $template
        );

        eval($template);
    }

    protected static function template()
    {
        $code = <<<CODE
namespace app\dynamicModels;

class {className} extends \yii\db\ActiveRecord
{
    public static function tableName()
    {
        return '{tableName}';
    }
}
CODE;
        return $code;
    }
}

spl_autoload_register(['DynamicModelFactory', 'autoload']);

然后修改您的 index.php 以在 Yii 自动加载器之前要求此自动加载脚本:

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/autoload.php'; // <- this is our autoloader
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

如果您需要 model class 的更复杂代码,您可以将其放入独立文件并使用file_get_content加载,而不是直接放入自动加载器 class。 您还可以添加代码,如果您愿意,可以在创建 model class 之前检查数据库中表的存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM