4

I have a Users and a Groups table in Laravel's Eloquent ORM. There can be multiple users in a group and a user can be in multiple groups, so I use a pivot table to realize the many-to-many relationship. In real, the relationship isn't many-to-many because every user can be in only one group, but the system was designed this way. I soft delete the rows in the Users table so if needed I can restore users later.

The problem is that when I delete a user, the system automatically delete the entry in the pivot table too. This is always one entry. I didn't set it to behave like this, only added the protected $softDelete = true; line to the Users model, so I don't understand why the system automatically delete the pivot entries.

I don't want to soft delete the pivot entries, I want to soft delete only and exclusively the users, and the system shouldn't touch anything else.
I could create my own delete function that set the deleted_at variable to the actual time but this way I couldn't simply turn of the soft delete by changing the true to false if I need this.

Why does the system automatically delete the pivot entries, and how can I turn off this behavior?

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
totymedli
  • 29,531
  • 22
  • 131
  • 165
  • Another answer is suggesting to add a constraint in your many-to-many relationship to filter, not exactly what you expected, also not sure if it works. http://stackoverflow.com/a/18144975/439427 – Rubens Mariuzzo Aug 12 '13 at 15:45
  • I meant to filter trashed relationships. – Rubens Mariuzzo Aug 12 '13 at 20:20
  • In my experience, when soft deleting a row it wont delete the pivot entries, can you give us an example of your Model and code? – SamV Sep 13 '13 at 17:11

1 Answers1

1

Check your database if you are using foreign keys you may have it set to ON UPDATE, ON DELETE "CASCADE". You need to set it up to "NO ACTION"

CONSTRAINT `fk_USER_Address_1` FOREIGN KEY (`userId`) REFERENCES `USER` (`userId`) ON UPDATE CASCADE ON DELETE CASCADE,

to

CONSTRAINT `fk_USER_Address_1` FOREIGN KEY (`userId`) REFERENCES `USER` (`userId`) ON UPDATE CASCADE ON DELETE NO ACTION,
Haver
  • 443
  • 2
  • 11