Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP save a three-model relationship association

Tags:

save

cakephp

I have the following output which I need to be inserted in the database:

Array
(
[Test] => Array
    (
    )

[Question] => Array
    (
        [0] => Array
            (
                [category_id] => 3
                [answer_style_id] => 2
                [Answer] => Array
                    (
                        [0] => Array
                            (
                                [capital_category_id] => 14
                                [correct] => 1
                            )

                       ...
         ...

Briefly, each Test hasMany Questions, and each Question hasMany Answer, with each associated model having a foreign key which need to be set by Cake (each Question has a test_id, and each Answer has a question_id).

The problem is that when I $this->Test->saveAll($data);, only the Test and the Questions get saved, not the answers.

How can I save all data, with Cake automagically setting the foreign key for each associated model?

Thank you!

like image 283
linkyndy Avatar asked Apr 08 '11 05:04

linkyndy


3 Answers

I'm not sure but I think it's impossible to save third level relation.

from Cakephp:

Saving related data with saveAll() will only work for directly associated models.

you'll have to retrieve third level data and save it apart from them.

like image 60
Headshota Avatar answered Nov 14 '22 02:11

Headshota


Yes, you can save deep model trees since CakePHP 2.1 this way

$this->SomeModel->saveAll($data, array('deep' => true));

Reference here > http://book.cakephp.org/2.0/en/appendices/new-features-in-cakephp-2-1.html#model-saveall-model-saveassociated-model-validateassociated

like image 43
steinkel Avatar answered Nov 14 '22 01:11

steinkel


I have three models A, B and C

A hasMany B B hasMany C

$A->saveAll() will save model A & B but not C

Here is a playaround I use:

in model B override afterSave like this

function afterSave($created) {
    if ($created) { // check if we are in save not update
        $this->data['B']['id'] = $this->id;
        $this->data['C'] = $this->data['B']['C'];
        $this->saveAll($this->data);
    }
}
like image 1
Saleh Ghaleb Avatar answered Nov 14 '22 01:11

Saleh Ghaleb