How to use events to add new data to the database in yii2. There are two related tables, and you need to track the event when an entry is added to one so that we add an entry to the second one.

I try so but something does not work event

And errors:

Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails public function addB() { $model2 = new NameDB(); $tim = round(microtime(true) * 1000); if($this->comment !== null){ $model2->comment = $this->comment; } if($this->userurl_password !== null){ $model2->userurl_password = $this->userurl_password; } Event::on($model2->save(), ActiveRecord::EVENT_AFTER_INSERT, function ($event) { //тут вызываем метод добавления записи в другую таблицу }); } 
  • maybe triggers are better to use in mysql habrahabr.ru/post/37693 - Naumov
  • Do not advise. I used to use them. - gilo1212
  • The text of the error tells you that it cannot update or insert a string, because the primary key is broken or not at all. According to the idea, you should just add a primary key for the table (entity). For example, if you add an id (as auto increment), then it will become the primary one. - Naumov

1 answer 1

The text of the error shows that the integrity constraints of data on foreign keys are violated ( foreign keys ).

Most likely, the foreign key that you are trying to insert into the second table is missing as the primary key in the first table.

In order to better understand what is happening there, it would be nice to give the CREATE TABLE query of your tables and the code for this place: //тут вызываем метод добавления записи в другую таблицу .

If you try, say, first, immediately after the event occurred, insert records into the table, and then from somewhere get the id inserted record from the first table, the one that triggered the event, and then update this record with this key (for example , $model->setSomeForeignKey($model2->id); $model->update(); ), this will not work, because inserting a row into the first table with a foreign key that is not in the second table causes an error , which you and flies.

Dig in this direction, look in yii's debugger for a list of queries, their sequence, check that at the time of inserting the record into the second table, the first table contains a record with the primary key referenced by the foreign key of the second table.