2016-10-31 15 views
0

私はコントローラのadd関数でcakephp 2を使用していますが、IDが存在する場合はデータを編集したい場合は作成しません。CakePHPが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)); 
      } 
     } 
    } 
} 

答えて

0
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

関連する問題