我试图在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;
}
}
Run Code Online (Sandbox Code Playgroud)
在我,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'
)
)));
}
Run Code Online (Sandbox Code Playgroud)
使用成分保存工作,但没有成分的保存不会,beforeSave返回之前Recipe-> data中的数据是这样的:
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'
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
当在保存之前添加成分时:
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'
)
)
)
)
Run Code Online (Sandbox Code Playgroud)
在我调用save方法之前数据在数组中时,只有当我尝试在beforeSave中添加关联数据时,它才能正常工作.
从文档:
确保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
| 归档时间: |
|
| 查看次数: |
638 次 |
| 最近记录: |