Cakephp add function if id exists edit else create

不羁岁月 提交于 2019-12-02 15:58:55

问题


I'm using cakephp 2 in my controller add function, I want to edit the data if the id exists, if not exists create.

This is my code in add function:

public function add () {

    if(!$this->request->data){
        throw new NotFoundException();
    }

    $googleCategory = $this->request->data;

    foreach ($googleCategory as $key => $value) {
        if(empty($value['category'])){
            unset($value);
        }

        $conditions = array (
            'AccountShopMeta.shop_id' => $value['shop_id'],
            'AccountShopMeta.name' => $value['category'],
            'AccountShopMeta.value' => $value['url_key']
        );

        if(!$this->AccountShopMeta->hasAny($conditions)){

            $this->AccountShopMeta->create();

            $data['shop_id'] = $value['shop_id'];
            $data['name'] = $value['category'];
            $data['value'] = $value['url_key'];
            $data['tag'] = '';

            if($this->AccountShopMeta->save($data)){
                $account_shop_meta = $this->AccountShopMeta->read();
                $this->set($account_shop_meta);
                $this->set('_serialize', array_keys($account_shop_meta));
            }
        }
    }
} 

回答1:


public function add () {

    if(!$this->request->data){
        throw new NotFoundException();
    }

    $googleCategory = $this->request->data;

    foreach ($googleCategory as $key => $value) {
        if(empty($value['category'])){
            unset($value);
        }

        $conditions = array (
            'AccountShopMeta.shop_id' => $value['shop_id'],
            'AccountShopMeta.name' => $value['category'],
            'AccountShopMeta.value' => $value['url_key']
        );

        $accountShopMeta = $this ->AccountShopMeta->find('first', $conditions);

        if(empty($accountShopMeta)) {
            //ADD
            $this->AccountShopMeta->create();
        } else {
           //EDIT
           $this->AccountShopMeta->id = $accountShopMeta['AccountShopMeta']['id'];
        }

        $data['shop_id'] = $value['shop_id'];
        $data['name'] = $value['category'];
        $data['value'] = $value['url_key'];
        $data['tag'] = '';

        if($this->AccountShopMeta->save($data)) {
            //This part shoud be out of loop (foreach)
            $account_shop_meta = $this->AccountShopMeta->read();
            $this->set($account_shop_meta);
            $this->set('_serialize', array_keys($account_shop_meta));
        }
    }

} 

More info Saving Your Data



来源:https://stackoverflow.com/questions/40338339/cakephp-add-function-if-id-exists-edit-else-create

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!