我试图在cakePHP beforeSave()期间添加相关数据,但看起来像cakePHP忽略了它。
<?php
App::uses("AppModel", "Model");
class Recipe extends AppModel {
public $hasMany = array('Ingredient');
public function beforeSave($options=array()) {
if(!isset($this->data["Ingredient"])) {
Debugger::log("data[Ingredient] didn't exist! adding some ingredients...");
$this->data["Ingredient"] = array(
array(
'Ingredient' => array(
'name' => 'Gluten Free Flour',
'amount' => '12 cups'
)
),
array(
'Ingredient' => array(
'name' => 'Sugar',
'amount' => '50 cups'
)
),
array(
'Ingredient' => array(
'name' => 'A shoe',
'amount' => 'Just one'
)
),
);
}
Debugger::log("Saving Data: ");
Debugger::log($this->data, 7, 10);
return true;
}
}
在我的RecipesController
我有这个:
public function test_save() {
//Test saving With the ingredients in the recipe
Debugger::log("Saving w/ ingredients");
Debugger::log($this->Recipe->saveAssociated(array(
'Recipe' => array(
'name' => 'Test Recipe 1'
),
'Ingredient' => array(
array(
'name' => 'Test Ingredient 1 for Test Recipe 1',
'amount' => 'a few'
),
array(
'name' => 'Test Ingredient 2 for Test Recipe 1',
'amount' => 'a lot'
)
)
)));
Debugger::log("Saving w/o ingredients");
Debugger::log($this->Recipe->saveAssociated(array(
'Recipe' => array(
'name' => 'Test Recipe 2'
)
)));
}
使用成分保存有效,但没有成分的保存没有,beforeSave
之前的食谱 - &gt;数据中的数据是:
array(
'Recipe' => array(
'name' => 'Test Recipe 1'
),
'Ingredient' => array(
(int) 0 => array(
'Ingredient' => array(
'name' => 'Test Ingredient 1 for Test Recipe 1',
'amount' => 'a few'
)
),
(int) 1 => array(
'Ingredient' => array(
'name' => 'Test Ingredient 2 for Test Recipe 1',
'amount' => 'a lot'
)
)
)
)
当在保存之前添加成分时:
array(
'Recipe' => array(
'name' => 'Test Recipe 1'
),
'Ingredient' => array(
(int) 0 => array(
'Ingredient' => array(
'name' => 'Gluten Free Flour',
'amount' => '12 cups'
)
),
(int) 1 => array(
'Ingredient' => array(
'name' => 'Sugar',
'amount' => '50 cups'
)
),
(int) 2 => array(
'Ingredient' => array(
'name' => 'A shoe',
'amount' => 'Just one'
)
)
)
)
当我调用save方法之前数据在数组中时,只有当我尝试在beforeSave中添加相关数据时,它才能正常工作。
答案 0 :(得分:6)
来自文档:
确保beforeSave()返回true,否则您的保存将失败。
http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave
已修改:我测试了您的代码并且您是对的,beforeSave()
中添加的相关数据被忽略。发生这种情况是因为您无法在模型beforeSave()
中添加或修改相关数据。这意味着,在您的食谱beforeSave()
中,您既不能添加配料,也不能修改之前添加到配方中的配料的配料。
在您的食谱beforeSave()
中,您只能修改配方数据。
这是一个错误吗?根据Mark Story(CakePHP的创始人)的说法,它不是:
它的一个功能,因为目前saveAll 只允许你使用beforeSave 修改即将保存的记录,而不是完整的数据集。一世 个人并不觉得应该改变,但它可以改变 讨论。
这句话大约是saveAll()
,但重要的部分是他对beforeSave()
所说的话。检查完整主题:https://github.com/cakephp/cakephp/issues/1765