spatie / laravel-event-projector

Event sourcing for Artisans 📽

Home Page:https://docs.spatie.be/laravel-event-projector

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Rebuilding / replaying. How to deal with foreign key constraints?

lukio3 opened this issue · comments

In the examples the resetState() function in the AccountProjector is as follows:

public function resetState()
  {
      Account::truncate();
  }

When rebuilding / replaying this function will be called to drop the rows in the accounts table.

However, if your Account model has relationships, and you have applied foreign key constraints to the same in your migrations, the rebuild/replay will fail with:

PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint

I have tried to get around this by adding to resetState():

Schema::disableForeignKeyConstraints();

(taking inspiration from the drop() in migrations)

or

DB::statement('SET FOREIGN_KEY_CHECKS=0;');

but neither seem to stop the 1701 SQL violation unfortunately. Has anybody else encountered this? If so how have you got around it?

We've encountered this as well. One way around it is using the DB facade instead of Eloquent: DB::statement('DELETE FROM accounts');.

Thanks @BasMulders

Just a word of caution for anybody else doing this.

If you have an auto-incrementing ID field then the counter will not be reset when using DB::statement('DELETE FROM accounts'); but it will be when using Account::truncate(); in your resetState method.

Thanks for the heads up, And yes, that's true. Although that's not a problem in our use-case since we're using uuid's as id's anyway.