CakePHP-如果关联模型验证失败,如何继续保存 [英] CakePHP - How to continue saving if associated model fails validation

查看:52
本文介绍了CakePHP-如果关联模型验证失败,如何继续保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组:

array(
    'Foo' => array(
        'field1' => 'value1',
        'field2' => 'value2'
    ),
    'Bar' => array(
        'field1' => 'value1',
        'field2' => 'value2'
    )
)

其中 Foo Bar 建立了模型关系,并在模型中具有自己的验证条件.

Where Foo and Bar have model relationships set up and have their own validation conditions in he model.

如何做到这一点,即使我执行 $ this-> Foo-> save(); ,即使 Bar 验证失败,它仍然会继续并仅保存 Foo

How can I make it so if I am doing $this->Foo->save(); even if Bar fails its validation then it will still go ahead and save Foo only

推荐答案

最终按照以下方式做点事情:

Ended up doing something along these lines:

如果初始保存失败,请检查是否存在 Bar 的验证错误,如果存在,则取消设置bar并再次保存,而 $中仅存在 Foo 数据

If initial save fails, check if there are validation errors for Bar, if there are, then unset bar and save again with just Foo present in $data

if ($this->Foo->save($data)) {
    //success
} else {
    $errors = $this->Foo->invalidFields();
    if (!empty($errors['Bar'])) {
        unset($data['Bar']);
    }

    //retry save
    if ($this->Foo->save($data) {
        //success
    } else {
        //failure
    }
}

这篇关于CakePHP-如果关联模型验证失败,如何继续保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆