laravel 现有表 生成 ORM 模型
use Illuminate\Support\Facades\Schema;
public function test()
{
$tables = Schema::getConnection()->getDoctrineSchemaManager()->listTableNames();
foreach ($tables as $table) {
$columns = Schema::getColumnListing($table);
$columns = implode("','",$columns);
$columns = "['$columns']";
$class = $table;
$tables = $table;
$class = explode('_', $class);
$className = '';
if (count($class) == 1) {
$className = $class[0];
} else {
for ($i = 1; $i < count($class); $i++) {
$className .= ucwords($class[$i]);
}
}
$path = 'Models\\' . ucwords($class[0]);
$path = app_path($path) . "\\";
if (!is_dir($path)) {
mkdir($path, 0777, true);
} else {
chmod($path, 0777);
}
$file = $className . '.php';
if (file_exists($path . $file)) {
echo $tables;
continue;
}
$r = fopen($path . $file, 'w');
$dir = ucwords($class[0]);
$text = "<?php
namespace App\Models\\$dir;
use Illuminate\Database\Eloquent\Model;
use App\Models\ModelTrait;
class $className extends Model
{
use ModelTrait;
/**
* 关联到模型的数据表
*
* @var string
*/
protected \$table = '$tables';
/**
* 表明模型是否应该被打上时间戳
*
* @var bool
*/
public \$timestamps = false;
protected \$fillable = $columns;
}
";
fwrite($r, $text);
fclose($r);
}
}