Yii2 使用 Gii 模型生成器在模型中创建自定义函数

Yii2 creating a custom function in the model using Gii model generator

我正在研究使用 Gii 生成模型的 Yii2。我想做的是自定义我的模型,使它们都具有以下功能

public static function getFoobarList() 
{
    $models = Foobar::find()->all();
    return ArrayHelper::map($models, 'id', 'foobar');
}

其中 Foobar 是个别模型的名称。

提前致谢。

由于您希望在所有模型中使用此功能,另一种解决方案是在 ActiveRecord 模型中添加此功能,所有生成的模型都从该模型扩展。您只需稍微更改功能即可执行所需的功能。

只需将此添加到您的 ActiveRecord class:

public static function getModelList() 
{
    $models = static::find()->all();
    return ArrayHelper::map($models, 'id', static::tableName());
}

要将此用于任何模型,例如 Foobar,您需要做的就是:

Foobar::getModelList();

您可以 create a custom template 为 gii 可以用来生成您的模型 class。

像下面这样的东西,添加到文件副本的顶部 /vendor/yiisoft/yii2-gii/generators/model/default/model.php 和新文件存储在,例如 @app/myTemplates/model/default

/**
 * your doc string
 */
 public static function get<?php echo $className; ?>List()
 {
    $models = static::find()->all();
    return ArrayHelper::map($models, 'id', static::tableName());
 }

会将您正在寻找的方法添加到使用新模板创建的任何模型中。

在您的配置中类似于

// config/web.php for basic app
// ...
if (YII_ENV_DEV) {    
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',      
        'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'],  
        'generators' => [ //here
            'model' => [ // generator name
                'class' => 'yii\gii\generators\model\Generator', // generator class
                'templates' => [ //setting for out templates
                    'myModel' => '@app/myTemplates/model/default', // template name => path to template
                ]
            ]
        ],
    ];
}

将允许您在使用 gii 时从 'Code Template' 菜单中 select 您的自定义模板。