EDIT: This question title originally was: How does Doctrine know last inserted id in MySQL? and was related to Doctrine ORM mapper. After some digging I found out that this question is not related to Doctrine but to PDO_MySQL, MySQL C API and finally - to MySQL client-server communication. I have decided to change the title, so maybe someone will find answer to his/hers question.
For those who are not using Doctrine: I was curious, why bellow:
mysql_query("INSERT INTO category (name) VALUES('cat')");
echo mysql_insert_id();
or similar:
$pdo->exec("INSERT INTO category (name) VALUES('cat')");
echo $pdo->lastInsertId();
will lead to only one position (without separate SELECT LAST_INSERT_ID()
) in log:
1701 Query INSERT INTO category (name) VALUES ('cat')
Original question:
I have 2 tables:
category(id,name)
product(id, name, categoryId)
I created new category object and product object. I assigned category object to product object. I didn't set any ids:
$product = new Product();
$product->name = 'asdf';
$category = new Category();
$category->name = 'cat';
$product->Category = $category;
After that I flushed the connection and check MySQL logs:
1684 Query START TRANSACTION
1684 Query INSERT INTO category (name) VALUES ('cat')
1684 Query INSERT INTO product (name, categoryid) VALUES ('asdf', '312')
1684 Query COMMIT
How did Doctrine know, that the newly created category id is 312? There is nothing else in logs.