Reputation: 2007
I have two tables, a TaskLists
table with an automatically generated primary key and a Tasks
table. A TaskList
can have multiple Tasks
.
How would I now insert a TaskLists
row and at the same time atomically insert none to multiple rows into the Tasks
table which reference the just inserted object.
Upvotes: 0
Views: 330
Reputation: 52107
According to general relativity, nothing in this universe happens at the "same time", so you can't. :)
However, you can start a transaction, insert a row into TaskList
, insert corresponding rows into Task
and then commit the transaction. That would certainly be "atomic" in a sense that you couldn't (permanently) write partial data in the database.
If TaskList
's ID is auto-incremented, you can get it via LAST_INSERT_ID
and then use it for Task
's FK.
Upvotes: 0
Reputation: 7244
Make use of triggers
that happends AFTER INSERT
CREATE TRIGGER trigger_name
AFTER INSERT
ON TaskList FOR EACH ROW
BEGIN
-- Insert the rows to tasks now
INSERT INTO tasks (TaskID) VALUES (NEW.TaskId);
-- You can run several insert statements here
END;
If you want to make use of the values from TaskList
, use the NEW.columname
https://www.techonthenet.com/mysql/triggers/after_insert.php
Upvotes: 0