I have two tables in my MySQL database, which were created like this:
CREATE TABLE table1 (
id int auto_increment,
name varchar(10),
primary key(id)
) engine=innodb
and
CREATE TABLE table2 (
id_fk int,
stuff varchar(30),
PRIMARY KEY (`id_fk`),
CONSTRAINT id_fk FOREIGN KEY(id_fk) REFERENCES table1(id) ON DELETE CASCADE
) engine=innodb
(These are not the original tables. The point is that table2 has a foreign key referencing the primary key in table 1)
Now in my code, I would like to add entries to both of the tables within one transaction. I'm doing this:
$table1 = new table1();
$table1->setTransaction($transaction);
$table1->name($name);
if (!$table->create()) {
foreach ($table1->getMessages() as $message) {
$this->flash->error($message);
}
$transaction->rollback("Can't save table1");
} else {
$table2 = new table2();
$table2->setTransaction($transaction);
$table2->setId($table1->getId());
$table2->setStuff($stuff);
if (!$table2->create()) {
foreach ($table2->getMessages() as $message) {
$this->flash->error($message);
}
$transaction->rollback("Can't save password");
}
$transaction->commit();
The table1 create() is successful, however, when I attempt the table2 create, it always errors out with a Constraint Violation stating that the Value of field "Id" does not exist on referenced table.How can I use phalcon transaction to save data into two referenced tables in a single transaction. Thanks.