laravel migrations : tips

PsOnly發表於2021-08-02
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();
        });
    }
$table->foreignId('user_id')->nullable()->constrained();

$table->foreignId('user_id')->constrained()->onDelete('cascade');
>  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
$table->timestamp('reviewed_at')->useCurrent();
$table->timestamp('reviewed_at')->useCurrentOnUpdate();

執行 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

執行命令 php artisan schema:dump,生成檔案 database/schema/mysql-schema.dump

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

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

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

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

本作品採用《CC 協議》,轉載必須註明作者和本文連結