我在我的一个项目中使用 CakePHP 2.1.3,我希望通过控制器以 JSON 格式返回模型验证错误,当我尝试通过 CakePHP 的模型属性 validationErrors 访问验证错误时,它在主要和所有其他关联时返回有效错误数组模型存在验证错误。但是,当主模型有效且关联模型存在验证错误时,它会导致无效的验证错误数组。下面是一个例子:
if ($this->request->is('post') || $this->request->is('put')) {
    if ($this->PrimaryModel->saveAll($this->request->data, array('validate' => 'first'))) {
        echo json_encode(array('success' => true));
    } else {
        $errors=array();
        $tablesToModels=$this->PrimaryModel->tableToModel; //List of table names included in the model description. Used for associations.
        foreach($tablesToModels as $tabel => $model) {
            $errors[$model]=$this->{$model}->validationErrors;
        }
        pr($errors);
        //echo json_encode(array('errors' => $errors));
    }
    exit;
}
如果主模型和关联模型存在验证错误,则上面的代码会产生以下输出:
Array
(
    [PrimaryModel] => Array
        (
            [field1] => Array
                (
                    [0] => notempty
                )
        )
    [AssociatedModel] => Array
        (
            [field1] => Array
                (
                    [0] => notempty
                )
            [field2] => Array
                (
                    [0] => notempty
                )
        )
)
当所有字段都填写在主模型中,或者主模型没有验证错误时,它会导致以下错误数组:
Array
(
    [PrimaryModel] => Array
        (
            [AssociatedModel] => Array
                (
                    [field1] => Array
                        (
                            [0] => notempty
                        )
                    [field2] => Array
                        (
                            [0] => notempty
                        )
                )
        )
    [AssociatedModel] => Array
        (
            [field1] => Array
                (
                    [0] => notempty
                )
            [field2] => Array
                (
                    [0] => notempty
                )
        )
)
我不知道为什么会发生这种情况以及我在哪里做错了什么?
这是一个编辑表单代码,以防你们需要它来整理它:
<php
    echo $this->Form->input('PrimaryModel.field1');
    echo $this->Form->input('PrimaryModel.field2');
    echo $this->Form->input('PrimaryModel.field3');
    echo $this->Form->input('PrimaryModel.field4');
    echo $this->Form->input('AssociatedModel.field1');
    echo $this->Form->input('AssociatedModel.field2');
    echo $this->Form->input('AssociatedModel.field3');
    echo $this->Form->input('PrimaryModel.field5');
?>
谢谢大家 :)