How to add an entry to the database if there are two related tables? Add on some event? That is, when an entry appears in one table only then we add an entry to three? With help what is this done?

Interested in a question for both yii2 and pure php

And errors:

Integrity constraint violation: 1452 can not add or update a row of foreign key constraint fails

    1 answer 1

    In pure PHP, this is done manually - that is, there are no events. But first, you need to determine which dependency between tables. For example, if the first table depends on the second one, you first add the second record, and then the first one.

    For example, if you added an entry to the second table, then, as a rule, both in the PDO and the built-in mysql libraries return the primary key of the entry (unless of course you use InnoDB). If the primary key is returned, then this entry is successfully added, boldly add the next entry dependent on it.

    If you want to automate it at the mysql level, then dig in the direction of mysql triggers. You can start from here . But using mysql triggers is highly discouraged because it is desirable not to add logic to the database level!

    • Thank. The triggers wrote, but I was advised not to get too involved with them, in order to avoid problems for the future .. But I’m not exactly sure yet. - gilo1212
    • @ gilo1212 The fact is that triggers must be used if you have a large project and you can afford at least one developer who will work only with DB (triggers, procedures ..) But if you have a small project, application logic is very important centralize - in order to organize code and avoid unexpected errors. Using triggers is tempting, but in actual practice, transferring logic to a DB will complicate debugging programs and finding errors. In addition, practice shows that with the change of the project, some triggers are removed and implemented manually. - Daniel Abyan