DDL
數(shù)據(jù)庫(kù)模式定義語(yǔ)言DDL(Data Definition Language),是用于描述數(shù)據(jù)庫(kù)中要存儲(chǔ)的現(xiàn)實(shí)世界實(shí)體的語(yǔ)言。Easyswoole提供了一個(gè)DDL庫(kù),方便用戶(hù)用于定義一個(gè)數(shù)據(jù)庫(kù)表結(jié)構(gòu)。
組件要求
- easyswoole / spl:^ 1.2
安裝方法
composer require easyswoole/ddl
倉(cāng)庫(kù)地址
基本使用
創(chuàng)建表(CreateTable)
use EasySwoole\DDL\Blueprint\Create\Table as CreateTable;
use EasySwoole\DDL\DDLBuilder;
use EasySwoole\DDL\Enum\Character;
use EasySwoole\DDL\Enum\Engine;
$scoreSql = DDLBuilder::create('score', function (CreateTable $table) {
$table->setIfNotExists()->setTableComment('成績(jī)表'); //設(shè)置表名稱(chēng)
$table->setTableCharset(Character::UTF8MB4_GENERAL_CI); //設(shè)置表字符集
$table->setTableEngine(Engine::INNODB); //設(shè)置表引擎
$table->int('id')->setIsUnsigned()->setIsAutoIncrement()->setIsPrimaryKey()->setColumnComment('自增ID');
$table->int('stu_id')->setIsUnsigned()->setColumnComment('學(xué)生id');
$table->int('course_id')->setIsUnsigned()->setZeroFill()->setColumnComment('課程id');
$table->float('score', 3, 1)->setColumnComment('成績(jī)');
$table->int('created_at', 10)->setColumnComment('創(chuàng)建時(shí)間');
$table->foreign(null,'stu_id','student','stu_id')
->setOnDelete(Foreign::CASCADE)->setOnUpdate(Foreign::CASCADE);
});
echo $scoreSql;
//結(jié)果如下:
CREATE TABLE IF NOT EXISTS `score` (
`id` int UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT '自增ID',
`stu_id` int UNSIGNED NOT NULL COMMENT '學(xué)生id',
`course_id` int UNSIGNED ZEROFILL NOT NULL COMMENT '課程id',
`score` float(3,1) NOT NULL COMMENT '成績(jī)',
`created_at` int(10) NOT NULL COMMENT '創(chuàng)建時(shí)間',
FOREIGN KEY (`stu_id`) REFERENCES `student` (`stu_id`) ON DELETE CASCADE ON UPDATE CASCADE
)
ENGINE = INNODB DEFAULT COLLATE = 'utf8mb4_general_ci' COMMENT = '成績(jī)表';
修改表(AlterTable)
use EasySwoole\DDL\Blueprint\Alter\Table as AlterTable;
use EasySwoole\DDL\DDLBuilder;
$alterStuScoreSql = DDLBuilder::alter('score', function (AlterTable $table) {
$table->setRenameTable('student_score')->setTableComment('學(xué)生成績(jī)表');
$table->modifyIndex('ind_score')->normal('ind_score', 'score')->setIndexComment('學(xué)生成績(jī)--普通索引');
$table->modifyForeign('fk_stu_id')->foreign('fk_stu_id', 'stu_id', 'student_info', 'stu_id');
});
echo $alterStuScoreSql;
//結(jié)果如下:
ALTER TABLE `score` RENAME TO `student_score`;
ALTER TABLE `student_score`
COMMENT = '學(xué)生成績(jī)表',
DROP INDEX `ind_score`,
ADD INDEX `ind_score` (`score`) COMMENT '學(xué)生成績(jī)--普通索引';
ALTER TABLE `student_score` DROP FOREIGN KEY `fk_stu_id`;
ALTER TABLE `student_score` ADD CONSTRAINT `fk_stu_id` FOREIGN KEY (`stu_id`) REFERENCES `student_info` (`stu_id`);
刪除表(DropTable)
use EasySwoole\DDL\DDLBuilder;
$dropStuScoreSql = DDLBuilder::drop('student_score');
echo $dropStuScoreSql;
//結(jié)果如下:
DROP TABLE `student`;