php 在Laravel迁移中更改外键约束

sq1bmfud  于 9个月前  发布在  PHP
关注(0)|答案(5)|浏览(85)

我有这个迁移文件

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

字符串
我想更新以在删除时级联外键,就像我已经运行了这个:

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


我该怎么做呢?是否有类似change()的外键?

efzxgjgh

efzxgjgh1#

删除外键,然后再次添加它并运行migrate。

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

字符串

qhhrdooz

qhhrdooz2#

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

$table->dropForeign('posts_user_id_foreign');

字符串
或者,你可以传递一个数组值,它将在删除时自动使用传统的约束名称:

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


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

exdqitrt

exdqitrt3#

您需要删除

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中工作

xhv8bpkk

xhv8bpkk4#

1.运行composer require doctrine/dbal
1.在迁移文件中,执行以下操作:

Schema::table('table_one', function (Blueprint $table) {
     $table->foreignId('table_two_id')
           ->change()
           ->constrained('table_two')
           ->onDelete('cascade');
 });

1.运行php artisan migrate

r1wp621o

r1wp621o5#

如何通过Controller
1.设置路线:

Route::get('foreignkeyforimg', "foreignkey@index");

字符串
1.创建具有外键名称的控制器。
1.从Migration类扩展的Foreignkey Controller。
1.转到数据库并从表中手动删除旧主键

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

相关问题