如何在 Laravel 中更新外键?

问题描述 投票:0回答:5

我有这个迁移文件

Schema::create('table_one', function(Blueprint $table) 
{ 
    $table->increments('id'); 
    $table->string('name'); 
    $table->integer('table_two_id')->unsigned(); 
    $table->foreign('table_two_id')->references('id')->on('table_two'); 
    $table->timestamps(); 
});

我想更新以使其->onDelete('cascade');

$table->foreign('table_two_id')->references('id')->on('table_two')->onDelete('cascade');

我怎样才能实现这个目标?有类似

->change();
之类的吗?

php laravel database laravel-5
5个回答
83
投票

删除外键,然后再次添加并运行迁移。

public function up()
{
    Schema::table('table_one', function (Blueprint $table) {
        $table->dropForeign(['table_two_id']);

        $table->foreign('table_two_id')
            ->references('id')
            ->on('table_two')
            ->onDelete('cascade');
    });
}

10
投票

Laravel 文档说:

要删除外键,您可以使用

dropForeign
方法。外键约束使用与索引相同的命名约定。因此,我们将连接表名和约束中的列,然后在名称后面加上“_foreign”后缀

$table->dropForeign('posts_user_id_foreign'); 

或者,您可以传递一个数组值,该值在删除时将自动使用常规约束名称:

$table->dropForeign(['user_id']);

https://laravel.com/docs/5.7/migrations#foreign-key-constraints


5
投票

您需要删除

     public function up()
    {
        Schema::table('<tableName>', function (Blueprint $table) {
            $table->dropForeign('<FK-name>');
            $table->dropColumn('<FK-columnName>');
        });
        Schema::table('<tableName>', function (Blueprint $table) {
            $table->foreignId('<FK-columnName>')->constrained()->cascadeOnDelete();
        });

    }

有两个查询。在 Laravel 8 上工作


4
投票
  1. composer require doctrine/dbal
  2. 在您的迁移文件中,执行以下操作:
    Schema::table('table_one', function (Blueprint $table) {
        $table->foreignId('table_two_id')
              ->change()
              ->constrained('table_two')
              ->onDelete('cascade');
    });
  1. php artisan migrate

-18
投票

如何通过控制器进行操作

1- 设置粗略:
路线::get('foreignkeyforimg', "foreignkey@index"); 2-使用外键名称创建控制器。
3-从迁移类扩展的外键控制器。
4-转到数据库并从表中手动删除旧主键

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class Foreignkey extends Migration
{
    function index(){

        Schema::table('images', function (Blueprint $table) {


            $table->foreign('sub_cat_id')
               ->references('id')
                ->on('subcategories')
                ->onDelete('cascade');
        });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.