Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

elqouent10's avatar

Maintaining Integrity when Saving Relations In Database

Is there a simple way to insert two sets of data into two different tables, and if one fails, to reverse the other entry? For example:

Suppose I have three classes, Zoo and Ape. An Zoo hasMany Ape.

Now suppose I have a form where I am creating a new Zoo, and there are fields that are saved in the the Zoo table (location, hours of operation), and there are fields that are saved in the Ape table (e.g. tricks, weight, registration number with Ape regulators (must be unique)).

Suppose you save this form, and the Zoo is successfully saved, but the Ape registration number turns out not to be unique for some reason and the database throws an error. Is there anyway to delete the previously saved Zoo entry? If it is not deleted, you'll have a Zoo with no animals.

I understand you can check for the uniqueness in the application layer by querying the Ape table first, but is there a way to solve this problem in one go?

I have looked into model events, but it appears that the "creating" event is fired BEFORE any attempted insert of Zoo into the database, which is before you would get the primary key information of Zoo to then use as a foreign key for Ape .

0 likes
2 replies

Please or to participate in this conversation.