Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically disable and enable foreign key check in laravel?

Tags:

php

mysql

laravel

I am trying to move entries from my old tables to the new one with the updated schema. The problem is, I have to move content from 10 tables with old config to 10 tables with the new config.

I am doing this with the help of console command. When I add the new table and execute the command, I get Duplicate entry error for the tables that already have data which is obvious.

When I try to use DB::connection('mysql_old')->table('users')->truncate();, It throws 1701 Cannot truncate a table referenced in a foreign key constraint Errror which is obvious too!

Here is how I am moving entries from old tables to the new one.

$entries = DB::connection('mysql_old')->table('users')->get();
DB::table('users')->truncate();
foreach($entries as $entry){
    $user = \App\User::create([
        'name' => $entry->name,
        'email' => $entry->email,
        'status' => $entry->status,
        'credits' => $entry->credits,
        'role' => $entry->user_role,
        'email_subscription' => $entry->email_subscription,
        'activation_key' => $entry->activation_key,
        'password' => $entry->password,
        'remember_token' => $entry->remember_token,
        'created_at' => $entry->created_at,
        'updated_at' => $entry->updated_at
    ]);
}

The only solution is to disable foreign key check before truncate and enable it again after truncate (I think). It is a relational database as obvious. So, is there any better way to complete this task?

I thought about giving a try to move entries from old table to the new one in a relational way but it is not possible in this case.

I can execute the command php artisan migrate:refresh every time the command is executed. But here is the problem with that, There are more than 25 tables and It takes about 20-30 seconds to complete migrate:refresh.

I am really confused how to get this done. Is there any proper or standard way?

like image 554
p01ymath Avatar asked Nov 14 '25 13:11

p01ymath


1 Answers

You can do this:

Schema::disableForeignKeyConstraints();

// Your database operations go here..

Schema::enableForeignKeyConstraints();
like image 162
Kenny Horna Avatar answered Nov 17 '25 07:11

Kenny Horna