想要实现酱婶儿滴模型注释
* @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 。就会生成上面的注释.