2012-01-31 89 views
3

我試圖用CakePHP的SaveAll()方法更新記錄,但是它增加了新行而不是更新它。saveAll()插入新行而不是更新

我的模型如下:商店hasOne地圖

class Store extends AppModel { 
    var $name = 'Store'; 

    var $hasOne = array(
     'Map' => array( 
      'className' => 'Map', 
      'foreignKey' => 'store_id', 
      'dependent' => true, 
      'exclusive' => true 
     ) 
    ); 
} 

我的編輯形式所具有的存儲ID(隱藏字段)告訴CakePHP的只更新特定的記錄。

<?php echo $this->Form->input('Store.id'); ?> 
<?php echo $this->Form->input('Store.name', array('label' => 'Store name', 'required')); ?> 
<?php echo $this->Form->input('Map.latlng', array('label' => 'Map location', 'required')); ?> 

我在Store控制器中的編輯方法如下。

if ($this->Store->saveAll($this->data)) { 
    $this->Session->setFlash('Store has been updated.'); 
    $this->redirect(array('controller' => 'store', 'action' => 'admin_index')); 
} 

每當我編輯一個存儲,商店名稱更新正常,但CakePHP不斷在Map表上插入一個新行。

我在這裏錯過了什麼嗎?由於

其他信息

我的調試($這個 - >數據)如下

Array 
(
    [Store] => Array 
     (
      [id] => 52 
      [name] => Sena The Accessorizer 
     ) 

    [Map] => Array 
     (
      [latlng] => 3.1580681, 101.7126311 
     ) 

) 
+0

顯示'$ this-> data'的調試 – Dunhamzzz 2012-01-31 15:11:18

+0

@Dunhamzzz問題已更新。謝謝 – 2012-01-31 15:22:07

+0

@John - 什麼是你的Form->創建? – Dave 2012-01-31 15:42:46

回答

3

正如@Dunhamzzz指出的那樣,Map沒有ID,因此CakePHP會插入一條新記錄。

爲了解決這個問題,我創建了一個隱藏字段用於Map.id

<?php echo $this->Form->input('Map.id'); ?> 

這將告訴CakePHP的更新而不是插入一個新的,特定的記錄。

2

如果要更新數據,而不是儲蓄,你應該總是設置你的ID想之前保存更新,就像這樣:

// Set the store ID 
$this->Store->id = $this->data['Store']['id']; 

// Then save using that id 
if ($this->Store->saveAll($this->data)) { 
    $this->Session->setFlash('Store has been updated.'); 
    $this->redirect(array('controller' => 'store', 'action' => 'admin_index')); 
} 
+0

該id已被設置爲他的形式(如您可以在他的數據陣列中看到) – Dave 2012-01-31 16:56:07

+0

仍然應該使用Oldskool的方法,因爲表單數據可以由最終用戶更改 – porjolovsky 2015-01-26 14:00:18

1

進行更新,你應該使用:

$this->Store->updateAll($this->data, array('Store.id' => $this->data['Store']['id'])); 
+1

不,您不應該在這種情況下。他正在更新一條記錄。全部更新可防止發生某些蛋糕操作(如更新修改的字段) – 2012-02-01 10:12:08

相關問題