enenen
enenen

Reputation: 1967

Get last inserted ID after inserting to associated table

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?

Upvotes: 2

Views: 1512

Answers (2)

Faisal
Faisal

Reputation: 4765

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.

Upvotes: 0

ADmad
ADmad

Reputation: 8100

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

Upvotes: 1

Related Questions