Laravel :: Best way to update a foreign key

后端 未结 4 1571
予麋鹿
予麋鹿 2020-12-05 18:06

I have this migration file

Schema::create(\'table_one\', function(Blueprint $table) 
{ 
    $table->increments(\'id\'); 
    $table->string(\'name\');          


        
相关标签:
4条回答
  • 2020-12-05 18:19

    Drop the foreign key then add it again and run 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');
        });
    }
    
    0 讨论(0)
  • 2020-12-05 18:36
    1. composer require doctrine/dbal
    2. In your migration file, do this:
        Schema::table('table_one', function (Blueprint $table) {
            $table->foreignId('table_two_id')
                  ->change()
                  ->constrained('table_two')
                  ->onDelete('cascade');
        });
    
    1. php artisan migrate
    0 讨论(0)
  • 2020-12-05 18:42

    Christopher K. is right, at the Laravel docs says:

    To drop a foreign key, you may use the dropForeign method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":

    $table->dropForeign('posts_user_id_foreign'); 
    

    Or, you may pass an array value which will automatically use the conventional constraint name when dropping:

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

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

    0 讨论(0)
  • 2020-12-05 18:42

    How to do via Controller

    1- Set a Rought:
    Route::get('foreignkeyforimg', "foreignkey@index"); 2- Create controller With Foreignkey Name.
    3- Foreignkey Controller with extend from Migration class.
    4- Go to database and delete old primary key manually from the table

    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');
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题