[TOC]
## 數據表創建:`Schema` facade 的 `create` 方法
`create` 方法接收兩個參數:
1. 數據表的名稱
2. 一個接收 `Blueprint` 實例 `$table` 的閉包,用于定義新數據表。
~~~php
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
});
~~~
>[info] 可以使用數據庫結構生成器的任何 [字段方法](database/columns.md) 來定義數據表的字段。
### 檢查數據表或字段是否存在:`Schema` facade 的 `hasTable` 和 `hasColumn` 方法
~~~php
if (Schema::hasTable('users')) {
//
}
if (Schema::hasColumn('users', 'email')) {
//
}
~~~
### 指定數據庫連接:`Schema` facade 的 `connection` 方法
在非默認的數據庫連接 `foo` 中進行數據庫結構操作:
~~~php
Schema::connection('foo')->create('users', function (Blueprint $table) {
$table->increments('id');
});
~~~
### 指定數據表屬性:在閉包里設置
命令 | 描述
--- | ---
`$table->engine = 'InnoDB';` | 設置MySQL數據表的存儲引擎。
`$table->charset = 'utf8';` | 設置MySQL數據表的字符集。
`$table->collation = 'utf8_unicode_ci';` | 設置MySQL數據表的排序規則。
~~~php
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
});
~~~
## 數據表重命名:`Schema` facade 的 `rename` 方法
~~~php
Schema::rename($from, $to);
~~~
### 重命名帶外鍵的數據表
在重命名前,你需要檢查[外鍵約束](#foreign-key-constraints)涉及到的數據表名,需要在遷移文件中顯式的提供,
而不是讓 Laravel 按照約定來設置一個名稱。因為那樣會讓外鍵約束關聯到舊的數據表上。
## 數據表刪除:`Schema` facade 的 `drop` 或 `dropIfExists` 方法
~~~php
Schema::drop('users');
Schema::dropIfExists('users');
~~~
## 數據表更新:`Schema` facade 的 `table` 方法
如同 `create` 方法,`table` 方法會接收兩個參數:
1. 數據表的名稱
2. 一個接收 `Blueprint` 實例 `$table` 的閉包,用于更新數據表。
~~~php
Schema::table('users', function (Blueprint $table) {
$table->string('email');
});
~~~
>[info] 可以使用任何數據庫結構構造器的 [字段方法](database/columns.md) 來定義數據表的字段。
- 日常命令
- 第一章 開發環境部署
- 第一節 安裝 VirtualBox
- 第二節 安裝 Vagrant
- 第三節 安裝 Git for Windows
- 命令行提示符的寫作約定
- Git Bash 使用技巧
- 第四節 安裝和配置 Homestead
- 第五節 啟動 Homestead 虛擬機
- 第六節 創建 Laravel 應用
- 第七節 使用 Git 進行版本控制
- 總結 本章命令概覽
- 第二章 前端工作流
- 第一節 Yarn 安裝前端擴展包
- 第二節 Laravel Mix 前端資源編譯
- (1)配置 webpack.mix.js 指定 Mix 任務
- (2)修改 resources/assets 前端資源文件
- (3)運行 Mix 任務編譯和監控代碼
- 總結 本章命令概覽
- 第三章 數據庫
- 第一節 Config 數據庫配置信息
- 第二節 Migrations 數據庫遷移文件
- 第三節 Schema 數據庫結構生成器
- (1) 數據表操作
- (2) 字段操作
- (3) 索引操作
- 第四節 Seeding 數據填充
- 第五節 DB 數據庫查詢構建器
- (1)獲取結果集