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!
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.
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With