I have a CakePHP 5 app, with two tables - Titles
and Series
.
Series
hasManyTitles
,Titles
table has aseries_id
propertyTitles
also haveseries_number
property
Imagine I have three titles, The Fellowship of the Ring, The Two Towers and The Return of the King. The titles are already in the DB, and I want to make a new Series. So I send some data to the endpoint like this:
{
"name": "The Lord of the Rings",
"titles": [
{ "id": 1, "series_number": 1 },
{ "id": 2, "series_number": 2 },
{ "id": 3, "series_number": 3 }
]
}
I want the new Series to update the existing titles, with the new series_id
and the series_number
property. I can’t just use _ids
for this cause I have additional data to save.
My save endpoint looks like this:
/**
* Add method
*
* @return void
* @throws \Cake\Http\Exception\InternalErrorException
*/
public function add(): void
{
$this->request->allowMethod(['post']);
$series = $this->Series->newEntity($this->request->getData(), ['associated' => ['Titles']]);
if ($this->Series->save($series)) {
$series = $this->Series->get($series->id, contain: ['Titles']);
} else {
throw new InternalErrorException('Could not save the series. Please try again later.');
}
$this->set(compact('series'));
$this->viewBuilder()->setOption('serialize', 'series');
}
However, when I process this request instead of updating the titles with ids 1,2,3 it just tries to create new ones. If I try to edit an existing series with titles, this request does work as the titles association is already contained on the entity I guess? But if I try to create a new series or update one that has no titles, it simply makes new ones.
Any help would be appreciated! Thanks.