0

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.

1 Answer 1

0

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

7
  • I've just tried but it's not working. Did you mean in the controller, right? Or I'm supposed to call the save* method in the beforeSave callback?
    – sangaran
    Commented Sep 3, 2013 at 21:29
  • yep, you call save method on the controller.. check this examples book.cakephp.org/2.0/en/models/…
    – pollirrata
    Commented Sep 3, 2013 at 21:34
  • Even this way the new associated data I "inject" in my beforeSave is not saved.
    – sangaran
    Commented Sep 3, 2013 at 21:42
  • wher are you injecting the data? You cannot modify $this->request->data ... you will need to create a copy of that array and then inject
    – pollirrata
    Commented Sep 3, 2013 at 21:46
  • In beforeSave. In that callback I have access to $this->data. I'mg adding the Tag key to the array as in my question example code.
    – sangaran
    Commented Sep 3, 2013 at 21:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.