laravel migrations : tips

foreign keys in laravel 7 and below

public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();

            //laravle 5.8- way
            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');

            //laralve 6+ way
            $table->unsignedBigInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users');

            //laravel 7+ way
            $table->foreignId('user_id')->constrained();
        });
    }

nullable() onDelete()

$table->foreignId('user_id')->nullable()->constrained();

$table->foreignId('user_id')->constrained()->onDelete('cascade');

migrations status

>  php artisan migrate:status
Ran? Migration Batch
Yes 2014_10_12_000000_create_users_table 1
Yes 2014_10_12_100000_create_password_resets_table 1
Yes 2014_10_12_200000_add_two_factor_columns_to_users_table 1
Yes 2019_08_19_000000_create_failed_jobs_table 1
Yes 2019_12_14_000001_create_personal_access_tokens_table 1
Yes 2021_04_02_125430_create_sessions_table 1
Yes 2021_04_03_063456_create_books_table 1
Yes 2021_04_03_083937_create_chapters_table 1
Yes 2021_04_03_084110_create_catalogs_table 1

Timestamps with Default Value

$table->timestamp('reviewed_at')->useCurrent();
$table->timestamp('reviewed_at')->useCurrentOnUpdate();

自定义 Default Migration File

运行 php artisan stub:publish 发布可以自定义stub,
在项目目录stubs/下,默认迁移文件 migration.create.stub

public function up(){
    Schema::create('{{table}}',function (Blueprint $table){
        $table->id();
        $table->timestamps();
        $table->softDeletes();
    });
}

再运行php artisan make:migration create_xx_table

导出all migrations 进一个sql文件

运行命令 php artisan schema:dump,生成文件 database/schema/mysql-schema.dump

删除列

$table->dropColumn('x1');
$table->dropColumn('x2');
$table->dropColumn(['x1','x2']);

回滚或刷新 x个步骤

php artisan migrate:rollback --step=2
php artisan migrate:refresh --step=2

自动递增的起始值

$table->id()->from(1000);

make migration

php artisan make:migration "add some fields to users table"
=
php artisan make:migration add_some_fields_to_users_table

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!