Cakephp 添加功能如果 id 存在编辑否则创建

Cakephp add function if id exists edit else create

我在我的控制器添加功能中使用 cakephp 2,如果 id 存在,我想编辑数据,如果不存在,则创建。

这是我在添加函数中的代码:

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));
            }
        }
    }
} 
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));
        }
    }

} 

更多信息Saving Your Data