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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

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