模型創建腳本
注冊腳本命令
ORM
提供了創建模型的命令,您可以很方便的根據數據表創建對應模型。不過這個功能目前僅限在 EasySwoole
框架中使用。
php easyswoole.php model gen -table={table_name}
在使用腳本之前需要先在 EasySwoole
框架中進行注冊 ORM
連接池和注冊創建腳本命令,修改 EasySwoole
框架根目錄的 bootstrap.php
文件,如下:
<?php
// bootstrap.php
// 全局bootstrap事件
date_default_timezone_set('Asia/Shanghai');
$argvArr = $argv;
array_shift($argvArr);
$command = $argvArr[0] ?? null;
if ($command === 'model') {
\EasySwoole\EasySwoole\Core::getInstance()->initialize();
}
\EasySwoole\Command\CommandManager::getInstance()->addCommand(new \EasySwoole\FastDb\Commands\ModelCommand());
創建模型
可選參數如下:
參數 | 類型 | 默認值 | 備注 |
---|---|---|---|
-db-connection | string | default | 連接池名稱,腳本會根據當前連接池配置創建 |
-path | string | App/Model | 模型路徑 |
-with-comments | bool | false | 是否增加字段屬性注釋 |
創建示例
在數據庫中先導入數據表 DDL
,如:
CREATE TABLE `easyswoole_user`
(
`id` int unsigned NOT NULL AUTO_INCREMENT COMMENT 'increment id',
`name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'name',
`status` tinyint unsigned DEFAULT '0' COMMENT 'status',
`score` int unsigned DEFAULT '0' COMMENT 'score',
`sex` tinyint unsigned DEFAULT '0' COMMENT 'sex',
`address` json DEFAULT NULL COMMENT 'address',
`email` varchar(150) COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT 'email',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
或數據庫已有上述數據表也可。
執行如下命令,創建模型:
php easyswoole.php model gen -table=easyswoole_user -with-comments
創建的模型如下:
<?php
declare(strict_types=1);
namespace App\Model;
use EasySwoole\FastDb\AbstractInterface\AbstractEntity;
use EasySwoole\FastDb\Attributes\Property;
/**
* @property int $id
* @property string|null $name
* @property int|null $status
* @property int|null $score
* @property int|null $sex
* @property string|null $address
* @property string|null $email
*/
class EasyswooleUser extends AbstractEntity
{
#[Property(isPrimaryKey: true)]
public int $id;
#[Property]
public ?string $name;
#[Property]
public ?int $status;
#[Property]
public ?int $score;
#[Property]
public ?int $sex;
#[Property]
public ?string $address;
#[Property]
public ?string $email;
public function tableName(): string
{
return 'easyswoole_user';
}
}