laravel中的数据库迁移

本文介绍如何使用Laravel框架创建数据库迁移文件,并演示了具体的迁移命令及步骤,包括创建迁移文件、编写迁移数据、设置Schema默认字符串长度以及执行迁移命令等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建数据库迁移文件:生成数据库迁移文件,前面跟着时间戳:

php  artisan  make:migration  create_posts_table

  

创建数据库迁移文件:可以重命名数据表名: --table和--create后面跟的都是表名:

php artisan make:migration create_users_table  --table=users

php artisan make:migration create_users_table  --create=users

在make:migration 后面可以跟:--path  跟上创建迁移文件的路径。

 

2.在创建的数据库迁移文件中,编写迁移数据:

<?php

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

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title',100)->default('');
            $table->text('content');
            $table->integer('user_id')->default(0);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations. reverse:背面;想反  
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

  

3.在app/providers/AppServiceProvider.php中填写,Schema的string默认长度,不然执行migrate命令,会报错。因为string的默认长度是1071,而数据库的最长长度小于他,所以会报错。

public function boot()
    {
        //mb4string
        Schema::defaultStringLength(250);
    }

 

4.执行数据库迁移命令:

php artisan migrate

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值