我在帐户和用户表之间有一对一的关系,我正在尝试在帐户模型的beforeSave
中进行所有预处理,但似乎我只能这样做更改$this->data['Account'][...]
而不是$this->data['User'][...]
的值,为什么会这样?
function beforeSave() {
// Check if this is a create or update action
if (empty($this->data['Account']['uid'])) {
$this->data['Account']['uid'] = uniqid();
$this->data['Account']['date_registration'] = date('Y-m-d');
$this->data['Account']['state'] = 1;
// this won't work
$this->data['User']['password'] = Security::hash($this->data['User']['password'], null, true);
}
return true;
}
另一个问题是检查用户是否在beforeSave事件中更新或创建模型的最佳方法是什么,检查empty($this->data['Account']['id']))
?
感谢。
答案 0 :(得分:1)
事实证明,它在CakePHP 1.3中是不可能的: http://cakephp.lighthouseapp.com/projects/42648/tickets/671-cant-modify-related-models-data-in-beforesave-when-using-saveall
我将代码移动到用户控制器,但这次问题是我无法直接访问$ this->帐户 - >名称,虽然我可以访问$ this-> Account-> id,这是为什么?我不得不做下面的工作场所:
function beforeSave() {
if (empty($this->date['User']['id'])){
$this->data['User']['password'] = Security::hash($this->data['User']['password'], null, true);
// Username is inherited from the account name
// TODO: the field needs to be removed, depending whether the Auth component will play nicely
$account_name = $this->Account->read('name',$this->Account->id);
$this->data['User']['username'] = $account_name['Account']['name'];
}
return true;
}