在CakePHP中自动创建$belongsTo相关模型


Automatically creating $belongsTo related Models in CakePHP

我有两个相关的模型,FooBar,其中Bar $belongsTo Foo。现在每个Foo必须有一个Bar,即两者必须同时创建。使用CakePHP的建模系统,是否有一种方法为被自动创建,每当Foo被创建(也许通过saveAll()),或者我应该把这个功能写进Foo::afterSave() ?

谢谢你的帮助

是的-只需使用构建您的数据为Foo和Bar,然后saveAll()

加上Dave的回答。

如果你的数据库表支持事务,通常是MySql的InnoDB storage engine。您还可以告诉Cake尝试一次保存两个记录。如果一个失败,另一个恢复。您需要将array('atomic' => true)作为第二个参数传递给saveAll()

$this->ModelName->saveAll($this->request->data, array("atomic" => true));

From CookBook

atomic: If true (default), will attempt to save all records in a single transaction. 
Should be set to false if database/table does not support transactions.