CakePHP:用户数据saveAll默默失败?

时间:2012-03-18 16:38:17

标签: cakephp cakephp-2.1

我有一个拥有多种乐器和流派的用户模型。使用以下代码时,仪器和流派保存:

$this->User->saveAll($this->data, array(
                'fieldList' => array('User', 'UserInstrument', 'Genre')))
        )

但用户没有。我的调试器(User, UserInstrument, Genre, UserGenre, Instrument)中的所有invalidFields数组都是空的。

我注意到的一个奇怪的事情就是在这里:

public function beforeSave() {
        // get the password reset
        if(isset($this->data[$this->alias]['password_reset'])) {
            $this->data[$this->alias]['password'] = $this->data[$this->alias]['password_reset'];
            unset($this->data[$this->alias]['password_reset']);
        }
        // get rid of the password confirm
        if(isset($this->data[$this->alias]['password_confirm'])) {
            unset($this->data[$this->alias]['password_confirm']);
        }
        // hash the password
        if (isset($this->data[$this->alias]['password'])) {
            $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
        }
        return true;
    }

我取消了password_resetpassword_confirm,但在保存完成后,这些字段会神奇地显示在$this->data['User']中(可能会从$_POST重新抓取)。但如果保存错误,那么saveAll将返回false。我的错误日志中没有任何内容。

关于为什么这是默默失败的任何想法?谢谢!

2 个答案:

答案 0 :(得分:1)

如果您的目的是为新创建的用户使用哈希,请参阅this

特别是beforeSave函数,它只是

public function beforeSave() {
    if (isset($this->data[$this->alias]['password'])) {
        $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
    }
    return true;
}

请理解,在cakephp中,如果包含实际上不在模型的数据表中的字段,则该字段将被忽略。因此,您无需为password_reset和password_confirm字段实际取消设置。

至于保存相关记录和使用fieldList,我注意到你没有明确说明要保存在数组的fieldList键中的字段。

此外,你说用户有很多乐器和用户有很多类型。

请使用saveAssociated方式。

在控制器中准备这样的数据:

$this->data['Instrument'] = array(
    array('instrument_field1'=>'v1',
           'instrument_field2' => 'v2',
         ),// first instrument
    array('instrument_field1' => 'v1',
          'instrument_field2' => 'v2')// second instrument
);

$this->data['Genre'] = array(
    array('field1'=>'v1',
           'field2' => 'v2',
         ),// first genre
    array('field1' => 'v1',
          'field2' => 'v2')// second genre
);

或者在表单中执行以下操作:

$this->Form->input('Instrument.0.field1'); // for the first instrument 
$this->Form->input('Instrument.1.field1'); // for the second instrument

如果我误解了这个问题,请回答我的回答。

答案 1 :(得分:0)

我拿出了fieldList。这不是最安全的解决方案,但这只是造成了比实际情况更麻烦的事情。

相关问题