【问题标题】:Laravel - How to add foreign key reference to already existing migrationLaravel - 如何将外键引用添加到已经存在的迁移
【发布时间】:2021-07-27 13:51:57
【问题描述】:

在我的 Larave-8 中,我使用此迁移创建了一个表:

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id');
        $table->string('first_name',50);
        $table->string('last_name',50);
        $table->string('other_name',50)->nullable();
        $table->string('gender',20);
        $table->string('user_photo',350)->nullable();
        $table->integer('nationality_id');
        $table->string('marital_status',50);
        $table->date('dob')->nullable();
        $table->string('address', 300)->nullable();
        $table->integer('country_id')->nullable();
        $table->integer('state_id')->nullable();
        $table->integer('city_id')->nullable();
        $table->string('cv_file',350)->nullable();
        $table->text('summary')->nullable();
        $table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
    });
}

如何通过迁移更改表并添加这些:

        $table->foreign('nationality_id')->references('id')->on('countries');
        $table->foreign('country_id')->references('id')->on('countries');
        $table->foreign('state_id')->references('id')->on('state_origins');
        $table->foreign('city_id')->references('id')->on('cities');

谢谢

【问题讨论】:

标签: laravel


【解决方案1】:

创建另一个迁移,例如更改现有表

public function up()
    {
        Schema::table('profiles', function (Blueprint $table) {
            $table->foreign('nationality_id')->references('id')->on('countries');
            $table->foreign('country_id')->references('id')->on('countries');
            $table->foreign('state_id')->references('id')->on('state_origins');
            $table->foreign('city_id')->references('id')->on('cities');
        });
    }

    public function down() {
        Schema::table('profiles', function (Blueprint $table) {
            $table->dropForeign('nationality_id');
            $table->dropForeign('country_id');
            $table->dropForeign('state_id');
            $table->dropForeign('city_id');
        });
    }

【讨论】:

    猜你喜欢
    • 2020-03-13
    • 2020-01-23
    • 2017-07-09
    • 2016-02-11
    • 2014-03-31
    • 1970-01-01
    • 2018-04-01
    • 2019-02-09
    • 2015-05-02
    相关资源
    最近更新 更多