Laravel 框架生成模型 property 注释

想要实现酱婶儿滴模型注释

 * @property   int  $id
 * @property   string  $username
 * @property   string  $password
 * @property   string  $name
 * @property   string  $avatar
 * @property   string  $remember_token
 * @property   \Carbon\Carbon  $created_at
 * @property   \Carbon\Carbon  $updated_at

1 执行命令 php artisan make:command GeneratModelAnnotation 生成命令类,会创建一个 app/Console/Commands/GeneratModelAnnotation.php文件3

2 将下面的代码赋值到GeneratModelAnnotation.php文件,此时,就完成了新命令的创建工作

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * 生成模型property注释
 * Class GeneratModelAnnotation
 *
 * @package App\Console\Commands
 */
class GeneratModelAnnotation extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'GMA {tableName}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成模型property注释,使得IDE有模型属性提示!';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
        $tableName  = $this->argument('tableName');
        $dbName     = config('database');
        $columns    = DB::select("
SELECT COLUMN_NAME, DATA_TYPE , COLUMN_COMMENT
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = '{$tableName}'
AND table_schema = '{$dbName['connections']['mysql']['database']}'");
        $annotation = "";
        foreach ($columns as $column) {
            $type = 'string';
            if (in_array($column->DATA_TYPE, ['int', 'tinyint', 'smallint', 'mediumint', 'bigint'])) {
                $type = 'int';
            } elseif (in_array($column->DATA_TYPE, ['float', 'double', 'decimal'])) {
                $type = 'float';
            }
            $columnName = $column->COLUMN_NAME;
            if (in_array($columnName, ['created_at', 'updated_at', 'deleted_at'])) {
                $type = '\\Carbon\\Carbon';
            }
            $columnComment = $column->COLUMN_COMMENT;
            $annotation    .= sprintf("\n * @property   %s  \$%s  %s", $type, $columnName, $columnComment);
        }
        $annotation .= "\n";
        echo($annotation);
//        file_put_contents('annotation',$annotation);
    }
}



3 最后使用格式为 php artisan gma TableName 的命令生成注释代码, TableName 为表名。如果要为表名为admin_users,那就执行 php artisan gma admin_users 。就会生成上面的注释.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值