【问题标题】:Why I can't change the data of another model in CakePHP为什么我不能在 CakePHP 中更改另一个模型的数据
【发布时间】:2010-09-16 00:07:48
【问题描述】:

我在帐户和用户表之间存在一对一的关系,我正在尝试在帐户模型的 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'])) 吗?

谢谢。

【问题讨论】:

    标签: cakephp model callback associations


    【解决方案1】:

    事实证明,在 CakePHP 1.3 中这是不可能的: http://cakephp.lighthouseapp.com/projects/42648/tickets/671-cant-modify-related-models-data-in-beforesave-when-using-saveall

    我把代码移到了用户控制器,但是这次的问题是我不能直接访问$this->Account->name,虽然我可以访问$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;
    }
    

    【讨论】:

    • $Model::id 是一个专门定义的属性。所有其他 数据 只能通过 $Model::data 访问,例如 $this->Account->data['Account']['name']
    • 超级有用。我试图编写一个可以在回调中修改子模型数据的行为。即使数据肯定在 $data 数组中,也无法将数据保存到数据库中。感谢分享!
    猜你喜欢
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多