防止saveAssociated保存空白关联数据

时间:2014-04-13 01:46:26

标签: php cakephp

如果关联数据的字段为空,如何保留saveAssociated保存关联数据的记录?我的应用正在运行CakePHP 2.4。

我在我的某个模型中包含图片上传,其中hasMany图像关系:它可以使用我表单中的$this->Form->input('Image.0.image'...字段成功添加附件。这些图片上传应该是可选的,但是当上传字段为空时,保存操作会为空白附件创建记录。

我已尝试检查此类请求数据,以查看图片字段是否为空,然后取消设置['Image']数组,但这似乎无效。

public function add() {
    if ($this->request->is('post')) {
            $this->Post->create();
            if (empty($this->request->data['Image'][0]['image'])) {
                unset($this->request->data['Image']);           
            }

            if ($this->Post->saveAssociated($this->request->data)) {
                $this->Session->setFlash(__('The post has been saved'), 'flash/success');
                $this->redirect(array('action' => 'view', $this->Post->id));
        } else {
            $this->Session->setFlash(__('The post could not be saved. Please, try again.'), 'flash/error');
        }
    }
}

1 个答案:

答案 0 :(得分:1)

这可能适合你 -

public function add() {
    if ($this->request->is('post')) {

            foreach($this->request->data['Image'] as $key => $value){
                if(empty($value['image'])){
                    unset($this->request->data['Image'][$key]);
                }
            }   
            $this->Post->create();

            if ($this->Post->saveAssociated($this->request->data)) {
                $this->Session->setFlash(__('The post has been saved'), 'flash/success');
                $this->redirect(array('action' => 'view', $this->Post->id));
        } else {
            $this->Session->setFlash(__('The post could not be saved. Please, try again.'), 'flash/error');
        }
    }
}