Get last inserted ID after inserting to associated table

1.5k views Asked by At

Employees table has a field named current_address_id. I'm adding a new address to Addresses like:

$updatedEntity = $this->patchEntity($employee, [
    //some other fields 
    'user'                => $userData,
    'employees_phones'    => $phonesData,
    'employees_addresses' => $addressesData,
], [
    'associated' => ['Users', 'EmployeesPhones', 'EmployeesAddresses']
]);
$this->save($updatedEntity);

I'm inserting the new address successfully but now I need to update Employees.current_address_id with the new address ID. How can I do this?

2

There are 2 answers

0
ADmad On BEST ANSWER

Table::save() returns the entity with updated ids. So store the return value in a variable and use appropriate property of the entity.

0
Faisal On

Try this one. It works for me.

$this->ModelName->save($updatedEntity);
$lastInsertedId = $updatedEntity->id; 

The save method will update the entity with the last insert id as long as the entity id is not already set.