Laravel 的数据库迁移的方法


Posted in PHP onJuly 31, 2017

本文介绍了Laravel 的数据库迁移的方法,分享给大家,具体如下:

生成迁移

--table 和 --create 选项可用来指定数据表的名称,或是该迁移被执行时会创建的新数据表。这些选项需在预生成迁移文件时填入指定的数据表:

php artisan make:migration create_users_table
php artisan make:migration create_users_table --create=users
php artisan make:migration add_votes_to_users_table --table=users

添加字段

\database\migrations\2017_07_30_133748_create_users_table.php

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
  /**
   * 运行数据库迁移
   *
   * @return void
   */
  public function up()
  {
    //
      Schema::create('users',function (Blueprint $table){
        $table->increments('id')->comment('递增ID');
        $table->string('email',60)->comment('会员Email');
        $table->string('phone',20)->comment('会员手机号');
        $table->string('username',60)->comment('用户名');
        $table->string('password',32)->comment('用户密码');
        $table->char('rank',10)->comment('会员等级');
        $table->unsignedSmallInteger('sex')->comment('性别;0保密;1男;2女');
        $table->unsignedSmallInteger('status')->comment('用户状态');
        $table->ipAddress('last_ip')->default('0.0.0.0')->comment('最后一次登录IP');
        $table->timeTz('last_login')->comment('最后一次登录时间');
        $table->timestamps();
      });
  }

  /**
   * 回滚数据库迁移
   *
   * @return void
   */
  public function down()
  {
    //
    Schema::drop('users');
  }
}

要创建一张新的数据表,可以使用 Schema facade 的 create 方法。create 方法接收两个参数:第一个参数为数据表的名称,第二个参数为一个 闭包 ,此闭包会接收一个用于定义新数据表的 Blueprint 对象

你可以方便地使用 hasTable 和 hasColumn 方法来检查数据表或字段是否存在:

if (Schema::hasTable('users')) {
  //
}
if (Schema::hasColumn('users', 'email')) {
  //
}

如果你想要在一个非默认的数据库连接中进行数据库结构操作,可以使用 connection 方法:

Schema::connection('foo')->create('users', function (Blueprint $table) {
  $table->increments('id');
});

你可以在数据库结构构造器上设置 engine 属性来设置数据表的存储引擎:

Schema::create('users', function (Blueprint $table) {
  $table->engine = 'InnoDB';
  $table->increments('id');
});

重命名与删除数据表

Schema::rename($from, $to);//重命名

//删除已存在的数据表
Schema::drop('users');
Schema::dropIfExists('users');

创建字段

Schema::table('users', function (Blueprint $table) {
  $table->string('email');
});

命令 描述
$table->bigIncrements('id'); 递增 ID(主键),相当于「UNSIGNED 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->dateTimeTz('created_at'); DATETIME (带时区) 形态
$table->decimal('amount', 5, 2); 相当于 DECIMAL 型态,并带有精度与基数。
$table->double('column', 15, 8); 相当于 DOUBLE 型态,总共有 15 位数,在小数点后面有 8 位数。
$table->enum('choices', ['foo', 'bar']); 相当于 ENUM 型态。
$table->float('amount', 8, 2); 相当于 FLOAT 型态,总共有 8 位数,在小数点后面有 2 位数。
$table->increments('id'); 递增的 ID (主键),使用相当于「UNSIGNED INTEGER」的型态。
$table->integer('votes'); 相当于 INTEGER 型态。
$table->ipAddress('visitor'); 相当于 IP 地址形态。
$table->json('options'); 相当于 JSON 型态。
$table->jsonb('options'); 相当于 JSONB 型态。
$table->longText('description'); 相当于 LONGTEXT 型态。
$table->macAddress('device'); 相当于 MAC 地址形态。
$table->mediumIncrements('id'); 递增 ID (主键) ,相当于「UNSIGNED MEDIUM INTEGER」型态。
$table->mediumInteger('numbers'); 相当于 MEDIUMINT 型态。
$table->mediumText('description'); 相当于 MEDIUMTEXT 型态。
$table->morphs('taggable'); 加入整数 taggable_id 与字符串 taggable_type。
$table->nullableMorphs('taggable'); 与 morphs() 字段相同,但允许为NULL。
$table->nullableTimestamps(); 与 timestamps() 相同,但允许为 NULL。
$table->rememberToken(); 加入 remember_token 并使用 VARCHAR(100) NULL。
$table->smallIncrements('id'); 递增 ID (主键) ,相当于「UNSIGNED SMALL INTEGER」型态。
$table->smallInteger('votes'); 相当于 SMALLINT 型态。
$table->softDeletes(); 加入 deleted_at 字段用于软删除操作。
$table->string('email'); 相当于 VARCHAR 型态。
$table->string('name', 100); 相当于 VARCHAR 型态,并带有长度。
$table->text('description'); 相当于 TEXT 型态。
$table->time('sunrise'); 相当于 TIME 型态。
$table->timeTz('sunrise'); 相当于 TIME (带时区) 形态。
$table->tinyInteger('numbers'); 相当于 TINYINT 型态。
$table->timestamp('added_on'); 相当于 TIMESTAMP 型态。
$table->timestampTz('added_on'); 相当于 TIMESTAMP (带时区) 形态。
$table->timestamps(); 加入 created_at 和 updated_at 字段。
$table->timestampsTz(); 加入 created_at and updated_at (带时区) 字段,并允许为NULL。
$table->unsignedBigInteger('votes'); 相当于 Unsigned BIGINT 型态。
$table->unsignedInteger('votes'); 相当于 Unsigned INT 型态。
$table->unsignedMediumInteger('votes'); 相当于 Unsigned MEDIUMINT 型态。
$table->unsignedSmallInteger('votes'); 相当于 Unsigned SMALLINT 型态。
$table->unsignedTinyInteger('votes'); 相当于 Unsigned TINYINT 型态。
$table->uuid('id'); 相当于 UUID 型态。

字段修饰

Schema::table('users', function (Blueprint $table) {
  $table->string('email')->nullable();
});

Modifier Description
->after('column') 将此字段放置在其它字段「之后」(仅限 MySQL)
->comment('my comment') 增加注释
->default($value) 为此字段指定「默认」值
->first() 将此字段放置在数据表的「首位」(仅限 MySQL)
->nullable() 此字段允许写入 NULL 值
->storedAs($expression) 创建一个存储的生成字段 (仅限 MySQL)
->unsigned() 设置 integer 字段为 UNSIGNED
->virtualAs($expression) 创建一个虚拟的生成字段 (仅限 MySQL)

字段更新

Schema::table('users', function (Blueprint $table) {
  $table->string('phone',20)->change();
  $table->string('username',60)->->nullable()->change();
});

重命名字段

Schema::table('users', function (Blueprint $table) {
  $table->renameColumn('from', 'to');
});

字段移除

Schema::table('users', function (Blueprint $table) {
  $table->dropColumn(['last_ip', 'last_login']);
});

在使用字段更新,重命名字段,字段移除之前,请务必在你的 composer.json文件require键名中添加< "doctrine/dbal": "^2.5">值。然后composer update进行更新或

composer require doctrine/dbal

创建索引

$table->string('email')->unique();

Command Description
$table->primary('id'); 加入主键。
$table->primary(['first', 'last']); 加入复合键。
$table->unique('email'); 加入唯一索引。
$table->unique('state', 'my_index_name'); 自定义索引名称。
$table->unique(['first', 'last']); 加入复合唯一键。
$table->index('state'); 加入基本索引。

开启和关闭外键约束

Schema::enableForeignKeyConstraints();
Schema::disableForeignKeyConstraints();

运行迁移

php artisan migrate

在线上环境强制执行迁移

php artisan migrate --force

回滚迁移

若要回滚最后一次迁移,则可以使用 rollback 命令。此命令是对上一次执行的「批量」迁移回滚,其中可能包括多个迁移文件:

php artisan migrate:rollback

在 rollback 命令后加上 step 参数,你可以限制回滚迁移的个数。例如,下面的命令将会回滚最后的 5 个迁移。

php artisan migrate:rollback --step=5

migrate:reset 命令可以回滚应用程序中的所有迁移:

php artisan migrate:reset

使用单个命令来执行回滚或迁移

migrate:refresh 命令不仅会回滚数据库的所有迁移还会接着运行 migrate 命令。所以此命令可以有效的重新创建整个数据库:

php artisan migrate:refresh
// 刷新数据库结构并执行数据填充
php artisan migrate:refresh --seed

使用 refresh 命令并加上 step 参数,你也可以限制执行回滚和再迁移的个数。比如,下面的命令会回滚并再迁移最后的 5 个迁移:

php artisan migrate:refresh --step=5

无法生成迁移文件

在 Laravel 项目中,由于测试,有时候用 PHP artisan make:migration create_xxx_table 创建数据库迁移。如果把创建的迁移文件 database/migrations/2017_07_30_133748_create_xxx_table.php 文件给删除了,再次执行 php artisan make:migration create_xxx_table 会报错:

[ErrorException]                                                                                                                                          

 include(E:\laraver\vendor\composer/../../database/migrations/2017_07_30_133748_create_users_table.php): failed to open stream: No such file or directory 

重新运行 composer update 又可以执行上面的命令了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
用 PHP5 轻松解析 XML
Dec 04 PHP
php采集时被封ip的解决方法
Aug 29 PHP
jQuery+php实现ajax文件即时上传的详解
Jun 17 PHP
解析PHP函数array_flip()在重复数组元素删除中的作用
Jun 27 PHP
PHP中使用SimpleXML检查XML文件结构实例
Jan 07 PHP
Codeigniter实现发送带附件的邮件
Mar 19 PHP
Yii2实现同时搜索多个字段的方法
Aug 10 PHP
PHP数组编码gbk与utf8互相转换的两种方法
Sep 01 PHP
PHP中list方法用法示例
Dec 01 PHP
iis6手工创建网站后无法运行php脚本的解决方法
Jun 08 PHP
PHP实现的迪科斯彻(Dijkstra)最短路径算法实例
Sep 16 PHP
laravel ajax curd 搜索登录判断功能的实现
Apr 17 PHP
PHP实现webshell扫描文件木马的方法
Jul 31 #PHP
PHP/ThinkPHP实现批量打包下载文件的方法示例
Jul 31 #PHP
Thinkphp结合AJAX长轮询实现PC与APP推送详解
Jul 31 #PHP
php实现将二维关联数组转换成字符串的方法详解
Jul 31 #PHP
微信接口生成带参数的二维码
Jul 31 #PHP
PHP判断一个数组是另一个数组子集的方法详解
Jul 31 #PHP
PHP中TP5 上传文件的实例详解
Jul 31 #PHP
You might like
历史证明,懒惰才是推动科学发展技术进步的动力
2021/03/02 无线电
基于ubuntu下nginx+php+mysql安装配置的具体操作步骤
2013/04/28 PHP
PHP中判断变量为空的几种方法分享
2013/08/26 PHP
[原创]PHPCMS遭遇会员投稿审核无效的解决方法
2017/01/11 PHP
JS中彻底删除JSON对象组成的数组中的元素
2020/09/22 PHP
解决iframe的frameborder在chrome/ff/ie下的差异
2010/08/12 Javascript
利用json获取字符出现次数的代码
2012/03/22 Javascript
JavaScript中的细节分析
2012/06/30 Javascript
jquery中插件实现自动添加用户的具体代码
2013/11/15 Javascript
js动态调用css属性的小规律及实例说明
2013/12/28 Javascript
JQuery实现样式设置、追加、移除与切换的方法
2015/06/11 Javascript
jQuery+JSON实现AJAX二级联动实例分析
2015/12/18 Javascript
JavaScript中split与join函数的进阶使用技巧
2016/05/03 Javascript
jQuery bt气泡实现悬停显示及移开隐藏功能的方法
2016/07/12 Javascript
Bootstrap响应式侧边栏改进版
2016/09/17 Javascript
jquery validation验证表单插件
2017/01/07 Javascript
解析Vue2.0双向绑定实现原理
2017/02/23 Javascript
vue的style绑定background-image的方式和其他变量数据的区别详解
2018/09/03 Javascript
如何阻止小程序遮罩层下方图层滚动
2019/09/05 Javascript
JS判断数组四种实现方法详解
2020/06/29 Javascript
浅谈vue中resetFields()使用注意事项
2020/08/12 Javascript
[01:18:21]EG vs TNC Supermajor小组赛B组败者组第一轮 BO3 第一场 6.2
2018/06/03 DOTA
下载给定网页上图片的方法
2014/02/18 Python
使用Python程序抓取新浪在国内的所有IP的教程
2015/05/04 Python
python3 通过 pybind11 使用Eigen加速代码的步骤详解
2020/12/07 Python
如何用 Python 处理不平衡数据集
2021/01/04 Python
工程概预算专业毕业生求职信
2013/10/04 职场文书
应届毕业生的个人自我鉴定
2013/10/24 职场文书
电子商务专业学生职业生涯规划
2014/03/07 职场文书
客户付款通知书
2015/04/23 职场文书
Python入门之使用pandas分析excel数据
2021/05/12 Python
解决Mysql的left join无效及使用的注意事项说明
2021/07/01 MySQL
MybatisPlus EntityWrapper如何自定义SQL
2022/03/22 Java/Android
mysql的单列多值存储实例详解
2022/04/05 MySQL
vue的项目如何打包上线
2022/04/13 Vue.js
Python中的协程(Coroutine)操作模块(greenlet、gevent)
2022/05/30 Python