DDL

数据库模式定义语言DDL(Data Definition Language),是用于描述数据库中要存储的现实世界实体的语言。Easyswoole提供了一个DDL库,方便用户用于定义一个数据库表结构。

组件要求

  • easyswoole / spl:^ 1.2

安装方法

composer require easyswoole/ddl

仓库地址

easyswoole/ddl

基本使用

创建表(CreateTable)

  1. use EasySwoole\DDL\Blueprint\Create\Table as CreateTable;
  2. use EasySwoole\DDL\DDLBuilder;
  3. use EasySwoole\DDL\Enum\Character;
  4. use EasySwoole\DDL\Enum\Engine;
  5. $scoreSql = DDLBuilder::create('score', function (CreateTable $table) {
  6. $table->setIfNotExists()->setTableComment('成绩表'); //设置表名称
  7. $table->setTableCharset(Character::UTF8MB4_GENERAL_CI); //设置表字符集
  8. $table->setTableEngine(Engine::INNODB); //设置表引擎
  9. $table->int('id')->setIsUnsigned()->setIsAutoIncrement()->setIsPrimaryKey()->setColumnComment('自增ID');
  10. $table->int('stu_id')->setIsUnsigned()->setColumnComment('学生id');
  11. $table->int('course_id')->setIsUnsigned()->setZeroFill()->setColumnComment('课程id');
  12. $table->float('score', 3, 1)->setColumnComment('成绩');
  13. $table->int('created_at', 10)->setColumnComment('创建时间');
  14. $table->foreign(null,'stu_id','student','stu_id')
  15. ->setOnDelete(Foreign::CASCADE)->setOnUpdate(Foreign::CASCADE);
  16. });
  17. echo $scoreSql;
  18. //结果如下:
  19. CREATE TABLE IF NOT EXISTS `score` (
  20. `id` int UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT COMMENT '自增ID',
  21. `stu_id` int UNSIGNED NOT NULL COMMENT '学生id',
  22. `course_id` int UNSIGNED ZEROFILL NOT NULL COMMENT '课程id',
  23. `score` float(3,1) NOT NULL COMMENT '成绩',
  24. `created_at` int(10) NOT NULL COMMENT '创建时间',
  25. FOREIGN KEY (`stu_id`) REFERENCES `student` (`stu_id`) ON DELETE CASCADE ON UPDATE CASCADE
  26. )
  27. ENGINE = INNODB DEFAULT COLLATE = 'utf8mb4_general_ci' COMMENT = '成绩表';

修改表(AlterTable)

  1. use EasySwoole\DDL\Blueprint\Alter\Table as AlterTable;
  2. use EasySwoole\DDL\DDLBuilder;
  3. $alterStuScoreSql = DDLBuilder::alter('score', function (AlterTable $table) {
  4. $table->setRenameTable('student_score')->setTableComment('学生成绩表');
  5. $table->modifyIndex('ind_score')->normal('ind_score', 'score')->setIndexComment('学生成绩--普通索引');
  6. $table->modifyForeign('fk_stu_id')->foreign('fk_stu_id', 'stu_id', 'student_info', 'stu_id');
  7. });
  8. echo $alterStuScoreSql;
  9. //结果如下:
  10. ALTER TABLE `score` RENAME TO `student_score`;
  11. ALTER TABLE `student_score`
  12. COMMENT = '学生成绩表',
  13. DROP INDEX `ind_score`,
  14. ADD INDEX `ind_score` (`score`) COMMENT '学生成绩--普通索引';
  15. ALTER TABLE `student_score` DROP FOREIGN KEY `fk_stu_id`;
  16. ALTER TABLE `student_score` ADD CONSTRAINT `fk_stu_id` FOREIGN KEY (`stu_id`) REFERENCES `student_info` (`stu_id`);

删除表(DropTable)

  1. use EasySwoole\DDL\DDLBuilder;
  2. $dropStuScoreSql = DDLBuilder::drop('student_score');
  3. echo $dropStuScoreSql;
  4. //结果如下:
  5. DROP TABLE `student`;