gewode's avatar

SQLite Foreign Keys with Set Null on Delete not working for PHPUnit test

I have added a foreign keys constraint in migration file for posts table to the user_id column. So, on delete user, I want to set the user_id column to null. So, I added this.

$table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('set null');

It is working on the MySQL database. But not working on SQLite PHPUnit test. I have enabled foreign key constraints for SQLite, but still not working.

Please guide How can I make it work?

0 likes
6 replies
s4muel's avatar

How exactly did you enable the foreign key constraints?

gewode's avatar

@S4MUEL - This is the snippet I added to the migration file.

public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->integer('user_id')->nullable();

            $table->foreign('user_id')
                ->references('id')
                ->on('users')
                ->onDelete('set null');
       });
    }
staudenmeir's avatar

This creates a foreign key, but doesn't enable foreign keys (which are disabled by default on SQLite).

Use Schema::enableForeignKeyConstraints(); or adjust the connection configuration.

1 like
s4muel's avatar

@GEWODE - you have to enable the foreign keys for the sqlite connection. i suggest using something like:

if (DB::connection() instanceof \Illuminate\Database\SQLiteConnection) {
    DB::statement(DB::raw('PRAGMA foreign_keys=on'));
}

in your tests common class (e.g. TestCase setUp() method or similar)

or update your laravel to >= 5.7.12 that has a simple option in config, which seems to be enabled by default https://github.com/laravel/laravel/blob/v5.7.19/config/database.php#L40 https://github.com/laravel/framework/blob/8dfb2ec90777368c09fdb065725136a7549620bd/CHANGELOG-5.7.md#v5712-2018-10-30

1 like
gewode's avatar

@s4muel @staudenmeir My current Laravel version is v5.7.19. And I have checked the configuration file and foreign keys constraints are enabled by default.

And I have also already tried Schema::enableForeignKeyConstraints(); but it did not worked.

1 like
staudenmeir's avatar

What's the result of dd(DB::select('PRAGMA foreign_keys')[0]);?

What does "not working" mean?

Please or to participate in this conversation.