How does Schema::disableForeignKeyConstraints in Laravel work for MySQL?

Viewed 425

When performing actions that requires foreign key contraints to be disabled, one can temporarily disable foreign key constraints to perform such an action, eg:

Schema::disableForeignKeyConstraints();
// Do good stuff
Schema::enableForeignKeyConstraints();

This made me think if the restraints are disabled in the schema for all connections?

Is it possible for another connection in another process to break the restraint between the disabling and enabling?

I've tried to test this by running Schema::disableForeignKeyConstraints(); in Tinker, and opening a new terminal to attempt to break some foreign key constraints - but they still apply, and I'm not sure why.

The Schema builder uses

public function disableForeignKeyConstraints()
{
    return $this->connection->statement(
        $this->grammar->compileDisableForeignKeyConstraints()
    );
}

and for MySQL, the compileDisableForeignKeyConstraints function is defined as

public function compileDisableForeignKeyConstraints()
{
    return 'SET FOREIGN_KEY_CHECKS=0;';
}

so it seems that running Schema::disableForeignKeyConstraints(); should simply disable the foreign key restraints for the entire schema - yet it seems to only work on a per-connection basis.

Is this a Laravel thing or a MySQL thing? How does it work?

0 Answers
Related