如何更新转换cakephp而不是主表
我在模型中添加了翻译行为,模型就在这里如何更新转换cakephp而不是主表,cakephp,internationalization,Cakephp,Internationalization,我在模型中添加了翻译行为,模型就在这里 App::uses('AppModel', 'Model'); class Category extends AppModel { public $hasMany = "Product"; public $validate = array( 'name' => array( 'rule' => 'notEmpty' ) ); public $actsAs =
App::uses('AppModel', 'Model');
class Category extends AppModel
{
public $hasMany = "Product";
public $validate = array(
'name' => array(
'rule' => 'notEmpty'
)
);
public $actsAs = array(
'Translate' => array(
'name','folder','show'
)
);
public $name = "Category";
public $translateModel = 'KeyTranslate';
}
这是用于更新模型的控制器
public function admin_edit_translate($id,$locale)
{
$this->Category->locale = $locale;
$category = $this->Category->findById($id);
if ($this->request->is('post') || $this->request->is('put')) {
$this->Category->id = $id;
if ($this->Category->save($this->request->data)) {
$this->Session->setFlash('Category translate has been updated');
//$this->redirect(array('action' => 'edit',$id));
} else {
$this->Session->setFlash('Unable to update category');
}
}
if (!$this->request->data) {
$this->request->data = $category;
}
}
我的问题是,我在类别数据库中有一个名称字段,当我更新或创建一个新的翻译时,它会用翻译后的值进行更新。如何避免出现这种情况您必须使用
Model::locale
值来设置保存在数据库中的代码语言这种情况发生的原因是TranslateBehavior使用beforeSave和afterSave等回调来保存翻译的内容,因此它需要让模型的保存操作继续,从而包含最后翻译的内容
您可以通过如下方式调用beforeSave和afterSave,诱使TranslateBehavior认为模型正在保存某些内容,从而绕过此问题:
$Model = $this->Category;
$Model->create($this->request->data);
$Model->locale = $locale;
$beforeSave = $Model->Behaviors->Translate->beforeSave($Model, array(
array(
'callbacks' => true
)
));
if($beforeSave) {
$Model->id = $id;
$Model->Behaviors->Translate->afterSave($Model, true);
}
这样,翻译将被保存,主表将保持不变。但这可能不是保存翻译的最佳方式。为什么需要保持主表不变?回调
Behavior::beforeSave
在Model::beforeSave
之前
但是,在真正保存之前,在Model::beforeSave
中修改Behavior::beforeSave
数据的最简单方法是:
$this->Behaviors->Behavior_Name->runtime[Model_Name]['beforeSave'][Field_Name] = '...';