roy404 / schema
Schema Builder 类是数据库层的一部分,允许您使用流畅的语法定义数据库表及其列。它提供了一种在不直接编写 SQL 查询的情况下创建和操作数据库表的方法。
1.0.1
2024-02-19 13:09 UTC
Requires
- php: ^8.0
README
使用 Composer 安装捆绑包
composer require roy404/schema
SQL Builder (Schema) 文档
简介
SQL Builder (Schema) 类提供了使用 PHP 构建和管理数据库模式流畅接口。它允许您以编程方式定义表、列、索引和其他模式元素。
用法
use Illuminate\Database\Facades\Schema; use Illuminate\Database\Facades\Blueprint; Schema::create('users', function (Blueprint $table) { $table->id( 'id' ); $table->string('name'); $table->dateTime( 'created_at' ); });
删除表
要删除现有的表,请使用 Schema::dropIfExists 方法并传递表名
Schema::dropIfExists('users');
检查表是否存在
要检查表是否存在,请使用 Schema::hasTable 方法并传递表名
if (Schema::hasTable('users')) { // Table exists } else { // Table does not exist }
列类型
tinyInt
:一个非常小的整数。smallInt
:一个小整数。mediumInt
:一个中等大小的整数。bigInt
:一个大整数。int
:一个整数。decimal
:一个指定小数点前后数字数量的定点数。float
:一个浮点数。double
:一个双精度浮点数。string
:一个可变长度的字符串。enum
:一个枚举,是一个字符串值的列表。blob
:一个二进制大对象,用于存储大二进制数据。text
:一个文本字符串,用于存储长文本数据。timestamp
:一个时间戳,用于存储日期和时间。date
:一个日期。dateTime
:一个日期和时间。time
:一个时间。year
:一个年份。
列修改器
autoIncrement
:使列成为自动增长的 主键。primary
:将列标记为主键。unique
:将列标记为具有唯一约束。index
:在列上创建索引。binary
:将列标记为二进制(用于二进制数据)。unsigned
:将列标记为无符号(用于非负整数)。on_update
:设置列在更新时更新为当前时间戳。current_date
:将列的默认值设置为当前时间戳。default
:为列设置默认值。nullable
:允许列包含 NULL 值。comment
:向列添加注释。collation
:设置列的校对。
示例
以下是一个创建具有一些列的表的示例
Schema::create( 'test', function( Blueprint $table ) { $table->int( 'id' )->primary()->autoIncrement(); $table->string( 'name' )->comment( "User full name" ); $table->string( 'email', 32 )->unique(); $table->enum( 'is_verified', [ '1', '0' ])->comment( 'Email is verified.' ); $table->dateTime( 'created_at' )->on_update(); });
结论
SQL Builder (Schema) 类为在 PHP 应用程序中定义和管理数据库模式提供了强大的方式。它简化了创建和修改表、列和索引的过程,使您能够专注于构建应用程序的逻辑。