You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.8 KiB
55 lines
1.8 KiB
<?php
|
|
|
|
|
|
namespace app\common\model;
|
|
|
|
use EasySwoole\DDL\Blueprint\Table;
|
|
use EasySwoole\DDL\DDLBuilder;
|
|
use EasySwoole\DDL\Enum\Character;
|
|
use think\facade\Db;
|
|
use think\Model;
|
|
|
|
abstract class BaseModel extends Model
|
|
{
|
|
protected static $instance;
|
|
protected $comment = "表名备注";
|
|
|
|
/**
|
|
* @return static
|
|
*/
|
|
public static function Inst()
|
|
{
|
|
$t = get_called_class();
|
|
if (empty(static::$instance[$t])) {
|
|
static::$instance[$t] = new static();
|
|
}
|
|
return static::$instance[$t];
|
|
}
|
|
|
|
/**
|
|
* 初始化表
|
|
*/
|
|
public function initTable()
|
|
{
|
|
$sql = DDLBuilder::table($this->getTable(), function (Table $table) {
|
|
$table->setIfNotExists()->setTableComment($this->comment); //设置表名称
|
|
$table->setTableCharset(Character::UTF8MB4_GENERAL_CI);//设置表字符集
|
|
$table->colInt('id')->setIsAutoIncrement()->setIsPrimaryKey()->setIsUnsigned()->setColumnComment('主键id');
|
|
$table->colDateTime('created_at')->setDefaultValue("CURRENT_TIMESTAMP")->setColumnComment('创建时间');
|
|
$table->colDateTime('updated_at')->setDefaultValue("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP")->setColumnComment('更新时间');
|
|
});
|
|
Db::query($sql);
|
|
$ori_fields = $this->db()->getTableFields($this->getTable());
|
|
$new_fields = $this->generateTableField();
|
|
$start = $ori_fields[count($ori_fields) - 3];
|
|
foreach ($new_fields as $k => $v) {
|
|
if (!in_array($k, $ori_fields)) {
|
|
$sql = "ALTER TABLE {$this->getTable()} add $v AFTER $start";
|
|
Db::execute($sql);
|
|
$start = $k;
|
|
}
|
|
}
|
|
}
|
|
|
|
abstract protected function generateTableField(): array;
|
|
}
|