laravel数据库迁移

12 篇文章 0 订阅
9 篇文章 0 订阅

一:创建迁移

在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();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值