php - CakePHP - How to add associated records to a model on save?
Get the solution ↓↓↓I'm using CakePHP 2.3 and I'm trying to find the correct way to perform associated data saving. I've setup an image upload form that save picture data but in the mean time I also want to process the saved image such that on save my application should examine the file and extract all the exif data and add that tags as associated models tags.
My relations are
Picture hasMany Tags
Tag belongsTo Picture
Right now I'm trying to use the Picture beforeSave callback to programmatically add the new records to the data array but it's not working (it's not saving the added data).
PictureController
$this->Picture->create();
$this->Picture->saveAll($this->request->data);
Data array after beforeSave
Array
(
[Picture] => Array
(
[field1] => foo
[field2] => bar
)
[Tag] => Array
(
[0] => Array
(
[tag] => example
[value] => example
)
[1] => Array
(
[tag] => example 2
[value] => example 2
)
)
)
How can I achieve what I want without messing too much with the controller? I would like my business logic to stay mostly on the model.
Answer
Solution:
You need to use deep in order to achieve this. According to the cookbook:
To save also associated data with $options['deep'] = true (since 2.1)
Examples
$Model->saveMany($data, array('deep' => true));
$Model->saveAssociated($data, array('deep' => true));
Check the cookbook for more details
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: call to undefined function mysqli_connect()
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.