I have got these two CakePHP V 2.4.5 models:
class Owner extends AppModel {
public $name = 'Owner';
public $hasMany = array('Car');
}
and
class Car extends AppModel {
public $name = 'Car';
public $belongsTo = array('Owner');
}
in my controller I wrote:
var $uses = array('Owner', 'Car');
public function test(){
$data = array(
'Owner' => array(
'name' => 'Me'
),
'Car' => array(
array('color' => 'red'),
array('color' => 'blue')
)
);
$this->Owner->saveAssociated($data, array('deep' => true));
}
But CakePHP created the owner and forgets to create his cars:
1 BEGIN
2 INSERT INTO `test`.`owners` (`name`) VALUES ('Me')
3 COMMIT
This is what my ERM looks like:
Why does CakePHP not save the cars?
Note : For transactions to work correctly in MySQL your tables must use InnoDB engine. Remember that MyISAM tables do not support transactions.
Not an actual answer but I've just tested your code and it works for me as well. (Cake 2.4.5)
If you try with a fresh instance of CakePHP only with these necessary models and controller is it still not working?
It's not possible to give a directly-working answer because: There's nothing wrong with the code in the question. That probably means you aren't running your own code at all.
Given that the only answer that can be given is advice, the only class that matters for the example in the question is
Owner
.Check filenames
The model conventions are:
Misnamed model files is by far the most common cause of "why is my model logic not being executed" questions. One pitfall is to add the suffix
Model.php
to model files, is the model file named correctly?In this case check that the file
app/Model/Owner.php
exists.Verify that the model is your model
If you're sure the model file is named correctly check what the app is using:
If the output is "AppModel" - the model file is not loaded. There are very few reasons why CakePHP will not use a file that exists and one of them will apply:
Verify the association exists
If
Car
is not in the output - the association isn't saved because to cake it doesn't exist - you'll need to identify why.Check which files are loaded
If in doubt, check which files are loaded at run time:
This may indicate that a different file is being loaded, which prevents
app/Model/Owner.php
from being loaded.Use a test to verify what's happening
You can use a test case to aide debugging for example:
Which should output:
Note that correctly one owner was created for "Me", and two cars - each linked to the owner record for "Me".
I'v tested your code.
It works perfect.
Try to remove models cache in /tmp/cache folder
My results:
Can you please try this:
Instead of
Thanks