溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Laravel中數(shù)據(jù)庫(kù)遷移的操作方法是什么

發(fā)布時(shí)間:2023-02-10 09:23:21 來(lái)源:億速云 閱讀:89 作者:iii 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了Laravel中數(shù)據(jù)庫(kù)遷移的操作方法是什么的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡(jiǎn)單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇Laravel中數(shù)據(jù)庫(kù)遷移的操作方法是什么文章都會(huì)有所收獲,下面我們一起來(lái)看看吧。

    一:創(chuàng)建遷移

    在laravel中使用make:migration命令來(lái)創(chuàng)建遷移

    php artisan make:migration create_user_table

    執(zhí)行上面的命令后這時(shí)候會(huì)在database/migrations 目錄下生成對(duì)應(yīng)的遷移文件,每個(gè)遷移的文件名都包含一個(gè)時(shí)間戳來(lái)讓 Laravel 確認(rèn)遷移的順序

    二:遷移結(jié)構(gòu)

    一個(gè)遷移類(lèi)包含兩個(gè)方法: up 和 down。up 方法是用于新增數(shù)據(jù)庫(kù)的數(shù)據(jù)表、字段或者索引的,而 down 方法應(yīng)該與 up 方法的執(zhí)行操作相反。

    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');
    }

    三:運(yùn)行遷移

    php artisan migrate

    大多數(shù)遷移操作都是破壞性的,這意味著也許會(huì)丟失數(shù)據(jù)。為了防止有人在生產(chǎn)環(huán)境數(shù)據(jù)中運(yùn)行這些命令,在執(zhí)行這些命令之前將提示你進(jìn)行確認(rèn)。如果要強(qiáng)制遷移命令在沒(méi)有提示的情況下運(yùn)行,請(qǐng)使用 --force 參數(shù)

    php artisan migrate --force

    四:遷移回滾

    php artisan migrate:rollback

    通過(guò)向 rollback 命令加上 step 參數(shù),可以回滾指定數(shù)量的遷移

    php artisan migrate:rollback --step=5

    migrate:reset 命令將會(huì)滾回你應(yīng)用程序所有的遷移:

    php artisan migrate:reset

    五:回滾后遷移

    migrate:refresh 命令將會(huì)在回滾你所有的遷移后執(zhí)行 migrate 命令。這個(gè)命令可以高效的重新創(chuàng)建你的整個(gè)數(shù)據(jù)庫(kù):

    php artisan migrate:refresh
     
    // 刷新數(shù)據(jù)庫(kù)并執(zhí)行數(shù)據(jù)庫(kù)填充
    php artisan migrate:refresh --seed

    六:可用字段類(lèi)型

    在laravel的數(shù)據(jù)庫(kù)遷移中,支持的字段類(lèi)型有:

    命令描述
    $table->bigIncrements('id');遞增 ID(主鍵),相當(dāng)于「UNSIGNED BIG INTEGER」
    $table->bigInteger('votes');相當(dāng)于 BIGINT
    $table->binary('data');相當(dāng)于 BLOB
    $table->boolean('confirmed');相當(dāng)于 BOOLEAN
    $table->char('name', 100);相當(dāng)于帶有長(zhǎng)度的 CHAR
    $table->date('created_at');相當(dāng)于 DATE
    $table->dateTime('created_at');相當(dāng)于 DATETIME
    $table->dateTimeTz('created_at');相當(dāng)于帶時(shí)區(qū) DATETIME
    $table->decimal('amount', 8, 2);相當(dāng)于帶有精度與基數(shù) DECIMAL
    $table->double('amount', 8, 2);相當(dāng)于帶有精度與基數(shù) DOUBLE
    $table->enum('level', ['easy', 'hard']);相當(dāng)于 ENUM
    $table->float('amount', 8, 2);相當(dāng)于帶有精度與基數(shù) FLOAT
    $table->geometry('positions');相當(dāng)于 GEOMETRY
    $table->geometryCollection('positions');相當(dāng)于 GEOMETRYCOLLECTION
    $table->increments('id');遞增的 ID (主鍵),相當(dāng)于「UNSIGNED INTEGER」
    $table->integer('votes');相當(dāng)于 INTEGER
    $table->ipAddress('visitor');相當(dāng)于 IP 地址
    $table->json('options');相當(dāng)于 JSON
    $table->jsonb('options');相當(dāng)于 JSONB
    $table->lineString('positions');相當(dāng)于 LINESTRING
    $table->longText('description');相當(dāng)于 LONGTEXT
    $table->macAddress('device');相當(dāng)于 MAC 地址
    $table->mediumIncrements('id');遞增 ID (主鍵) ,相當(dāng)于「UNSIGNED MEDIUM INTEGER」
    $table->mediumInteger('votes');相當(dāng)于 MEDIUMINT
    $table->mediumText('description');相當(dāng)于 MEDIUMTEXT
    $table->morphs('taggable');相當(dāng)于加入遞增的 taggable_id 與字符串 taggable_type
    $table->uuidMorphs('taggable');相當(dāng)于加入 taggable_id 與字符串 taggable_typeUUID 列。
    $table->multiLineString('positions');相當(dāng)于 MULTILINESTRING
    $table->multiPoint('positions');相當(dāng)于 MULTIPOINT
    $table->multiPolygon('positions');相當(dāng)于 MULTIPOLYGON
    $table->nullableMorphs('taggable');相當(dāng)于可空版本的 morphs () 字段
    $table->nullableUuidMorphs('taggable');相當(dāng)于可空版本的 uuidMorphs() 字段
    $table->nullableTimestamps();相當(dāng)于可空版本的 timestamps() 字段
    $table->point('position');相當(dāng)于 POINT
    $table->polygon('positions');相當(dāng)于 POLYGON
    $table->rememberToken();相當(dāng)于可空版本的 VARCHAR (100) 的 remember_token 字段
    $table->set('flavors', ['strawberry', 'vanilla']);相當(dāng)于 SET
    $table->smallIncrements('id');遞增 ID(主鍵),相當(dāng)于「UNSIGNED SMALLINT」
    $table->smallInteger('votes');相當(dāng)于 SMALLINT
    $table->softDeletes();相當(dāng)于為軟刪除添加一個(gè)可空的 deleted_at 字段
    $table->softDeletesTz();相當(dāng)于為軟刪除添加一個(gè)可空的 帶時(shí)區(qū)的 deleted_at 字段
    $table->string('name', 100);相當(dāng)于帶長(zhǎng)度的 VARCHAR
    $table->text('description');相當(dāng)于 TEXT
    $table->time('sunrise');相當(dāng)于 TIME
    $table->timeTz('sunrise');相當(dāng)于帶時(shí)區(qū)的 TIME
    $table->timestamp('added_on');相當(dāng)于 TIMESTAMP
    $table->timestampTz('added_on');相當(dāng)于帶時(shí)區(qū)的 TIMESTAMP
    $table->timestamps();相當(dāng)于可空的 created_at 和 updated_at TIMESTAMP
    $table->timestampsTz();相當(dāng)于可空且?guī)r(shí)區(qū)的 created_at 和 updated_at TIMESTAMP
    $table->tinyIncrements('id');相當(dāng)于自動(dòng)遞增 UNSIGNED TINYINT
    $table->tinyInteger('votes');相當(dāng)于 TINYINT
    $table->unsignedBigInteger('votes');相當(dāng)于 Unsigned BIGINT
    $table->unsignedDecimal('amount', 8, 2);相當(dāng)于帶有精度和基數(shù)的 UNSIGNED DECIMAL
    $table->unsignedInteger('votes');相當(dāng)于 Unsigned INT
    $table->unsignedMediumInteger('votes');相當(dāng)于 Unsigned MEDIUMINT
    $table->unsignedSmallInteger('votes');相當(dāng)于 Unsigned SMALLINT
    $table->unsignedTinyInteger('votes');相當(dāng)于 Unsigned TINYINT
    $table->uuid('id');相當(dāng)于 UUID
    $table->year('birth_year');相當(dāng)于 YEAR

    七:字段修飾

    在laravel的數(shù)據(jù)庫(kù)遷移中,支持的字段修飾符有:

    命令描述
    ->after('column')將此字段放置在其它字段 "之后" (MySQL)
    ->autoIncrement()將 INTEGER 類(lèi)型的字段設(shè)置為自動(dòng)遞增的主鍵
    ->charset('utf8')指定一個(gè)字符集 (MySQL)
    ->collation('utf8_unicode_ci')指定列的排序規(guī)則 (MySQL/SQL Server)
    ->comment('my comment')為字段增加注釋 (MySQL)
    ->default($value)為字段指定 "默認(rèn)" 值
    ->first()將此字段放置在數(shù)據(jù)表的 "首位" (MySQL)
    ->nullable($value = true)此字段允許寫(xiě)入 NULL 值(默認(rèn)情況下)
    ->storedAs($expression)創(chuàng)建一個(gè)存儲(chǔ)生成的字段 (MySQL)
    ->unsigned()設(shè)置 INTEGER 類(lèi)型的字段為 UNSIGNED (MySQL)
    ->useCurrent()將 TIMESTAMP 類(lèi)型的字段設(shè)置為使用 CURRENT_TIMESTAMP 作為默認(rèn)值
    ->virtualAs($expression)創(chuàng)建一個(gè)虛擬生成的字段 (MySQL)
    ->generatedAs($expression)使用指定的序列生成標(biāo)識(shí)列(PostgreSQL)
    ->always()定義序列值優(yōu)先于標(biāo)識(shí)列的輸入 (PostgreSQL)
    ->primary('id')添加主鍵
    ->primary(['id', 'parent_id'])添加復(fù)合鍵
    ->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)

    實(shí)例:

    Schema::table('users', function (Blueprint $table) {
        $table->string('email')->nullable();
    });

    八:修改字段

    change 方法可以將現(xiàn)有的字段類(lèi)型修改為新的類(lèi)型或修改屬性,例:

    Schema::table('users', function (Blueprint $table) {
        $table->string('name', 50)->change();
    });

    renameColumn方法來(lái)重命名字段,依賴于doctrine/dbal拓展,例:

    Schema::table('users', function (Blueprint $table) {
        $table->renameColumn('from', 'to');
    });

    九:刪除字段

    dropColumn 方法來(lái)刪除字段,例:

    Schema::table('users', function (Blueprint $table) {
        $table->dropColumn(['votes', 'avatar', 'location']);//刪除votes,avatar,location字段
    });

    十:索引長(zhǎng)度 & Mysql / MariaDB

    Laravel 默認(rèn)使用 utf8mb4 編碼,它支持在數(shù)據(jù)庫(kù)中儲(chǔ)存 emojis 。如果你是在版本低于 5.7.7 的 MySQL 或者版本低于 10.2.2 的 MariaDB 上創(chuàng)建索引,那你就需要手動(dòng)配置數(shù)據(jù)庫(kù)遷移的默認(rèn)字符串長(zhǎng)度。即在 app/Providers/AppServiceProvider 中調(diào)用 Schema::defaultStringLength 方法來(lái)配置它

    use Illuminate\Support\Facades\Schema;
     
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    十一:外鍵約束

    Laravel 還支持創(chuàng)建用于在數(shù)據(jù)庫(kù)層中的強(qiáng)制引用完整性的外鍵約束。例如,讓我們?cè)?posts 表上定義一個(gè)引用 users 表的 id 字段的 user_id 字段:

    Schema::table('posts', function (Blueprint $table) {
        $table->unsignedBigInteger('user_id');
     
        $table->foreign('user_id')->references('id')->on('users');
    });

    在遷移文件中使用以下方法來(lái)開(kāi)啟或關(guān)閉外鍵約束

    Schema::enableForeignKeyConstraints();
     
    Schema::disableForeignKeyConstraints();

    關(guān)于“Laravel中數(shù)據(jù)庫(kù)遷移的操作方法是什么”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“Laravel中數(shù)據(jù)庫(kù)遷移的操作方法是什么”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問(wèn)一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI