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_resetand password_confirm,但是在保存完成后,这些字段会神奇地重新出现$this->data['User'](可能是从 重新抓取的$_POST)。但如果保存时出错,则saveAll返回 false。我的错误日志中也没有任何内容。

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

4

2 回答 2

1

如果您的目的是为新创建的用户使用散列,请查阅

尤其是 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 键中明确说明要保存的字段。

此外,您说 User hasMany Instrument 和 User hasMany Genre。

请使用 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

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

于 2012-03-20T01:35:01.097 回答
0

我拿出来fieldList。不是最安全的解决方案,但这只会带来比其价值更多的麻烦。

于 2012-04-13T19:05:14.690 回答