Thursday, November 26, 2015

Deep save associated models with relation back to first model

I have 3 models: A, B, C.

A hasMany B

A hasMany C

B hasMany C

        A
       
/ \
     
/   \
     
/     \
   
|       |
   
^       ^
    B
----< C



I created the view and the controller add method.

The forms data:

$data = array(
    'A' => array(
    'id' => '',
    'name' => 'alpha',
    'B' => array(
    'id' => '',
    'name' => 'beta',
    'C' => array(
    'id' => '',
    'name' => 'gamma'
    )
    )
    )
    )



I save the forms data with the `$this->A->saveAssociated($data, ['deep' => true])` call.

If I query the newly created A model, I get the following data:

array(
    'A' => array(
    'id' => (int) 111,
    'name' => 'alpha',
    'B' => array(
    'id' => (int) 9,
    'a_id' => (int) 111,
    'name' => 'beta',
    'C' => array(
    'id' => (int) 78,
    'b_id' => (int) 9,
    'a_id' => (int) 0,
    'name' => 'gamma'
    )
    )
    )
    )



My problem is that C models `a_id` field doesnt has good value / isnt related to the newly created A model.


Is it possible to save them with one `saveAssociated($data, ['deep' => true])` call?
I think I need a way to override Cake foreign key setter method during save.

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP

---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cake-php+unsubscribe@googlegroups.com.
To post to this group, send email to cake-php@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php.
For more options, visit https://groups.google.com/d/optout.

No comments: