Schema Builder
Laravel 提供 Schema 類別來操作資料表。通常會用在 migration 檔案中。
建立資料表
Schema::create('posts', function($table) {
$table->increments('id');
$table->string('title');
$table->string('content');
$table->timestamps();
});
等效 SQL:
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL DEFAULT '',
`content` varchar(255) NOT NULL DEFAULT '',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
)
資料表重新命名
Schema::rename($from, $to);
範例:
Schema::rename('posts', 'articles');
等效 SQL:
ALTER TABLE `posts`
RENAME TO `articles`;
刪除資料表
Schema::drop('posts');
或
Schema::dropIfExists('posts');
等效 SQL:
DROP TABLE `posts`;
新增欄位
Schema::table('posts', function($table)
{
$table->string('tag');
});
string 會被轉換成 varchar(255)。
等效 SQL:
ALTER TABLE `posts`
ADD `tag` varchar(255);
各種指令所代表的資料型態的列表:
註:因為各家資料庫的資料型態略有不同,Schema 指令會自動轉換成符合該資料庫所使用的資料型態。
指令
說明
$table->bigIncrements('id');
做為 id 的自動遞增欄 位,相當於 "big integer" 型態
$table->bigInteger('votes');
相當於 BIGINT 型態
$table->binary('data');
相當於 BLOB 型態
$table->boolean('confirmed');
相當於 BOOLEAN 型態
$table->char('name', 4);
相當於 CHAR 型態
$table->date('created_at');
相當於 DATE 型態
$table->dateTime('created_at');
相當於 DATETIME 型態
$table->decimal('amount', 5, 2);
相當於 DECIMAL 型態
$table->double('column', 15, 8);
相當於 DOUBLE 型態,15 是數值長度,8 是小數點位數
$table->enum('choices', array('foo', 'bar'));
相當於 ENUM 型態
$table->float('amount');
相當於 FLOAT 型態
$table->increments('id');
當作主鍵的自動遞增欄位,INTEGER 型態
$table->integer('votes');
相當於 INTEGER 型態
$table->longText('description');
相當於 LONGTEXT 型態
$table->mediumInteger('numbers');
相當於 MEDIUMINT 型態
$table->mediumText('description');
相當於 MEDIUMTEXT 型態
$table->nullableTimestamps();
相當於 TIMESTAMP 型態,但允許 NULL 值
$table->smallInteger('votes');
相當於 SMALLINT 型態
$table->tinyInteger('numbers');
相當於 TINYINT 型態
$table->softDeletes();
使用 deleted_at 欄位當做軟刪除的記錄欄位
$table->string('email');
相當於 VARCHAR 型態
$table->string('name', 100);
相當於 VARCHAR(100) 型態
$table->text('description');
相當於 TEXT 型態
$table->time('sunrise');
相當於 TIME 型態
$table->timestamp('added_on');
相當於 TIMESTAMP 型態
$table->timestamps();
加入 created_at 和 updated_at 欄位做為當資料[建立]及[更新]時間記錄之用
$table->rememberToken();
remember_token 欄位,相當於 VARCHAR(100) NULL 型態,儲存 session 資料
->nullable()
當該欄位允許 NULL 值時,可以串接這個方法
->default($value)
當要設定該欄位的預設值時串接使用
->unsigned()
指定 INTEGER 型態為 UNSIGNED 型態
刪除欄位
Schema::table('posts', function($table)
{
$table->dropColumn('tag');
});
等效 SQL:
ALTER TABLE `posts`
DROP COLUMN `tag`;
欄位重新命名
Schema::table('posts', function($table)
{
$table->renameColumn('from', 'to');
});
等效 SQL:
ALTER TABLE `posts`
RENAME COLUMN `from` to `to`;
Last updated
Was this helpful?