2017-02-09 34 views
0

我有一类产品型号:更改与saveMany多行的字段值()

class Item extends AppModel { 
    … 
    public $hasAndBelongsToMany = array(
     'Category' => 
      array(
       'className'    => 'Category', 
       'joinTable'    => 'categories_items', 
       'foreignKey'    => 'item_id', 
       'associationForeignKey' => 'category_id', 
       'unique'     => true, 
       'conditions'    => '', 
       'fields'     => '', 
       'order'     => '', 
       'limit'     => '', 
       'offset'     => '', 
       'finderQuery'   => '', 
       'deleteQuery'   => '', 
       'insertQuery'   => '' 
      ) 
    ); 
    … 
} 

我对对方同样的事情,类别。这意味着我有一个名为CategoriesItems的连接表。

我想为所有行更新项目表的一个字段。

$dataSource = $this->Item->getDataSource(); 
    $dataSource->begin(); 
    $items = $this->Item->find('all'); 
    $i = 1; 

    $data = array(); 
    foreach($items as $item) { 
     if($i == $newPosition) { 
      $movingItem['Item']['position'] = $newPosition; 
      $data[] = $movingItem; 
      $i++; 
     } 
     $item['Item']['position'] = $i; 
     $data[] = $item; 
     $i++; 
    } 
    if($this->Item->saveMany($data, array('deep' => true))) { 
     $dataSource->commit(); 
     $this->autoRender = false; 
     header("HTTP/1.0 200 OK"); 
     return true; 
    } 
    else { 
     $dataSource->rollback(); 
     $this->autoRender = false; 
     header("HTTP/1.0 404 Not Found"); 
     return false; 
    } 

看来我的数据数组很好。但是当我尝试保存它时,CategoriesItems行被删除。

回答

0

我终于找到了解决方案。

数据必须是这样的:

$i = 1; 
$data = []; 
foreach($items as $item) { 
    $data[] = ['Item' => ['id' => $item['Item']['id'], 'position' => $i]]; 
    $i++; 
}