Laravel中数据库迁移操作的示例详解

作者:huaweichenai 时间:2023-05-25 06:27:38 

一:创建迁移

在laravel中使用make:migration命令来创建迁移

php artisan make:migration create_user_table

执行上面的命令后这时候会在database/migrations 目录下生成对应的迁移文件,每个迁移的文件名都包含一个时间戳来让 Laravel 确认迁移的顺序

二:迁移结构

一个迁移类包含两个方法: up 和 down。up 方法是用于新增数据库的数据表、字段或者索引的,而 down 方法应该与 up 方法的执行操作相反。

1:up方法

public function up()
{
   Schema::create('user', function (Blueprint $table) {
       $table->bigIncrements('id');
       $table->string('name');
       $table->string('email')->unique();
       $table->timestamp('email_verified_at')->nullable();
       $table->string('password');
       $table->rememberToken();
       $table->timestamps();
   });
}

2:down方法

public function down()
{
   Schema::dropIfExists('user');
}

三:运行迁移

php artisan migrate

大多数迁移操作都是破坏性的,这意味着也许会丢失数据。为了防止有人在生产环境数据中运行这些命令,在执行这些命令之前将提示你进行确认。如果要强制迁移命令在没有提示的情况下运行,请使用 --force 参数

php artisan migrate --force

四:迁移回滚

php artisan migrate:rollback

通过向 rollback 命令加上 step 参数,可以回滚指定数量的迁移

php artisan migrate:rollback --step=5

migrate:reset 命令将会滚回你应用程序所有的迁移:

php artisan migrate:reset

五:回滚后迁移

migrate:refresh 命令将会在回滚你所有的迁移后执行 migrate 命令。这个命令可以高效的重新创建你的整个数据库:

php artisan migrate:refresh

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

六:可用字段类型

在laravel的数据库迁移中,支持的字段类型有:

命令描述
$table->bigIncrements('id');递增 ID(主键),相当于「UNSIGNED BIG INTEGER」
$table->bigInteger('votes');相当于 BIGINT
$table->binary('data');相当于 BLOB
$table->boolean('confirmed');相当于 BOOLEAN
$table->char('name', 100);相当于带有长度的 CHAR
$table->date('created_at');相当于 DATE
$table->dateTime('created_at');相当于 DATETIME
$table->dateTimeTz('created_at');相当于带时区 DATETIME
$table->decimal('amount', 8, 2);相当于带有精度与基数 DECIMAL
$table->double('amount', 8, 2);相当于带有精度与基数 DOUBLE
$table->enum('level', ['easy', 'hard']);相当于 ENUM
$table->float('amount', 8, 2);相当于带有精度与基数 FLOAT
$table->geometry('positions');相当于 GEOMETRY
$table->geometryCollection('positions');相当于 GEOMETRYCOLLECTION
$table->increments('id');递增的 ID (主键),相当于「UNSIGNED INTEGER」
$table->integer('votes');相当于 INTEGER
$table->ipAddress('visitor');相当于 IP 地址
$table->json('options');相当于 JSON
$table->jsonb('options');相当于 JSONB
$table->lineString('positions');相当于 LINESTRING
$table->longText('description');相当于 LONGTEXT
$table->macAddress('device');相当于 MAC 地址
$table->mediumIncrements('id');递增 ID (主键) ,相当于「UNSIGNED MEDIUM INTEGER」
$table->mediumInteger('votes');相当于 MEDIUMINT
$table->mediumText('description');相当于 MEDIUMTEXT
$table->morphs('taggable');相当于加入递增的 taggable_id 与字符串 taggable_type
$table->uuidMorphs('taggable');相当于加入 taggable_id 与字符串 taggable_typeUUID 列。
$table->multiLineString('positions');相当于 MULTILINESTRING
$table->multiPoint('positions');相当于 MULTIPOINT
$table->multiPolygon('positions');相当于 MULTIPOLYGON
$table->nullableMorphs('taggable');相当于可空版本的 morphs () 字段
$table->nullableUuidMorphs('taggable');相当于可空版本的 uuidMorphs() 字段
$table->nullableTimestamps();相当于可空版本的 timestamps() 字段
$table->point('position');相当于 POINT
$table->polygon('positions');相当于 POLYGON
$table->rememberToken();相当于可空版本的 VARCHAR (100) 的 remember_token 字段
$table->set('flavors', ['strawberry', 'vanilla']);相当于 SET
$table->smallIncrements('id');递增 ID(主键),相当于「UNSIGNED SMALLINT」
$table->smallInteger('votes');相当于 SMALLINT
$table->softDeletes();相当于为软删除添加一个可空的 deleted_at 字段
$table->softDeletesTz();相当于为软删除添加一个可空的 带时区的 deleted_at 字段
$table->string('name', 100);相当于带长度的 VARCHAR
$table->text('description');相当于 TEXT
$table->time('sunrise');相当于 TIME
$table->timeTz('sunrise');相当于带时区的 TIME
$table->timestamp('added_on');相当于 TIMESTAMP
$table->timestampTz('added_on');相当于带时区的 TIMESTAMP
$table->timestamps();相当于可空的 created_at 和 updated_at TIMESTAMP
$table->timestampsTz();相当于可空且带时区的 created_at 和 updated_at TIMESTAMP
$table->tinyIncrements('id');相当于自动递增 UNSIGNED TINYINT
$table->tinyInteger('votes');相当于 TINYINT
$table->unsignedBigInteger('votes');相当于 Unsigned BIGINT
$table->unsignedDecimal('amount', 8, 2);相当于带有精度和基数的 UNSIGNED DECIMAL
$table->unsignedInteger('votes');相当于 Unsigned INT
$table->unsignedMediumInteger('votes');相当于 Unsigned MEDIUMINT
$table->unsignedSmallInteger('votes');相当于 Unsigned SMALLINT
$table->unsignedTinyInteger('votes');相当于 Unsigned TINYINT
$table->uuid('id');相当于 UUID
$table->year('birth_year');相当于 YEAR

七:字段修饰

在laravel的数据库迁移中,支持的字段修饰符有:

命令描述
->after('column')将此字段放置在其它字段 "之后" (MySQL)
->autoIncrement()将 INTEGER 类型的字段设置为自动递增的主键
->charset('utf8')指定一个字符集 (MySQL)
->collation('utf8_unicode_ci')指定列的排序规则 (MySQL/SQL Server)
->comment('my comment')为字段增加注释 (MySQL)
->default($value)为字段指定 "默认" 值
->first()将此字段放置在数据表的 "首位" (MySQL)
->nullable($value = true)此字段允许写入 NULL 值(默认情况下)
->storedAs($expression)创建一个存储生成的字段 (MySQL)
->unsigned()设置 INTEGER 类型的字段为 UNSIGNED (MySQL)
->useCurrent()将 TIMESTAMP 类型的字段设置为使用 CURRENT_TIMESTAMP 作为默认值
->virtualAs($expression)创建一个虚拟生成的字段 (MySQL)
->generatedAs($expression)使用指定的序列生成标识列(PostgreSQL)
->always()定义序列值优先于标识列的输入 (PostgreSQL)
->primary('id')添加主键
->primary(['id', 'parent_id'])添加复合键
->unique('email')添加唯一索引
->index('state')添加普通索引
->spatialIndex('location')添加空间索引(不支持 SQLite)
->renameIndex('from', 'to')重命名索引
->dropPrimary('users_id_primary')删除主键
->dropUnique('users_email_unique');删除唯一索引
>dropIndex('geo_state_index');删除基本索引
->dropSpatialIndex('geo_location_spatialindex');删除空间索引(不支持 SQLite)

实例:

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

八:修改字段

change 方法可以将现有的字段类型修改为新的类型或修改属性,例:

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

renameColumn方法来重命名字段,依赖于doctrine/dbal拓展,例:

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

九:删除字段

dropColumn 方法来删除字段,例:

Schema::table('users', function (Blueprint $table) {
   $table->dropColumn(['votes', 'avatar', 'location']);//删除votes,avatar,location字段
});

十:索引长度 & Mysql / MariaDB

Laravel 默认使用 utf8mb4 编码,它支持在数据库中储存 emojis 。如果你是在版本低于 5.7.7 的 MySQL 或者版本低于 10.2.2 的 MariaDB 上创建索引,那你就需要手动配置数据库迁移的默认字符串长度。即在 app/Providers/AppServiceProvider 中调用 Schema::defaultStringLength 方法来配置它

use Illuminate\Support\Facades\Schema;

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
   Schema::defaultStringLength(191);
}

十一:外键约束

Laravel 还支持创建用于在数据库层中的强制引用完整性的外键约束。例如,让我们在 posts 表上定义一个引用 users 表的 id 字段的 user_id 字段:

Schema::table('posts', function (Blueprint $table) {
   $table->unsignedBigInteger('user_id');

   $table->foreign('user_id')->references('id')->on('users');
});

在迁移文件中使用以下方法来开启或关闭外键约束

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();

来源:https://blog.csdn.net/huaweichenai/article/details/128932815

标签:Laravel,数据库,迁移
0
投稿

猜你喜欢

  • thinkphp5实用入门进阶知识点和各种常用功能代码汇总

    2023-05-25 02:48:34
  • SQL截取字符串函数分享

    2011-11-03 17:07:37
  • 如何由Sybase向SQL Server移植数据库

    2009-01-20 15:56:00
  • 微软的jQuery国际化插件

    2010-07-02 12:46:00
  • MySQL数据库生产环境的维护工作总结的经验

    2011-12-01 10:20:52
  • js 返回 utf-8 字符编码是多少个字节, 函数 fUtf8BoundCheck

    2010-07-31 18:59:00
  • 快速认识CSS中的overflow属性

    2009-05-29 16:36:00
  • 请谨慎对待程序的图标和名称

    2011-06-16 20:35:22
  • 基于ASPJPEG 制作了一个梦寐已久的批量水印工具步骤

    2011-02-28 10:39:00
  • 网页版面布局的方法及技巧

    2007-10-29 12:41:00
  • asp中的rs.open与conn.execute的区别说明

    2011-02-24 10:56:00
  • 图片滤镜效果[IE Only]

    2009-06-14 19:49:00
  • QCon大会散记

    2010-05-03 14:19:00
  • 企业网站该怎么做?

    2009-06-29 16:11:00
  • CSS高级文字排版的实例

    2009-03-24 20:56:00
  • asp 过滤尖括号内所有内容的正则代码

    2011-04-03 10:40:00
  • IE7异常CSS 导致内存破坏漏洞

    2009-11-30 12:52:00
  • 浅析SQL Server 2008企业级新特性

    2008-11-24 17:01:00
  • 通过不同的CSS设计字体大小来提高用户体验

    2008-12-10 19:17:00
  • ASP模拟MVC模型的编程方式

    2008-10-15 14:51:00
  • asp之家 网络编程 m.aspxhome.com