How can I get the last insert id with doctrine 2 ORM? I didn't find this in the documentation of doctrine, is this even possible?
How can I get the last insert id with doctrine 2 ORM? I didn't find this in the documentation of doctrine, is this even possible?
A bit late to answer the question. But,
If it's a MySQL database
should $doctrine_record_object->id work if AUTO_INCREMENT is defined in database and in your table definition.
In my case, as I declared $id as private I just created a new public method to get it.
public function getId() {
return $this->id;
}
So then I could call it like so
$user = new User();
$user->setUsername("Kylo Ren");
$entityManager = getEntityManager();
$entityManager->persist($user);
$entityManager->flush();
echo "Created User with ID " . $user->getId() . "\n";
Here i post my code, after i have pushed myself for one working day to find this solution.
Function to get the last saved record :
private function getLastId($query) {
$conn = $this->getDoctrine()->getConnection();
$stmt = $conn->prepare($query);
$stmt->execute();
$lastId = $stmt->fetch()['id'];
return $lastId;
}
Another Function which call the above function
private function clientNum() {
$lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
$noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
return $noClient;
}