【问题标题】:saveAll() inserts new row instead of updatingsaveAll() 插入新行而不是更新
【发布时间】:2012-01-31 15:09:12
【问题描述】:

我正在尝试使用 CakePHP SaveAll() 方法更新记录,但是它会添加新行而不是更新它。

我的模型如下:A Store hasOne Map

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 表上插入新行。

我在这里遗漏了什么吗?谢谢

其他信息

我的调试($this->data)如下

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

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

)

【问题讨论】:

  • 显示$this-&gt;data的调试
  • @Dunhamzzz 问题已更新。谢谢
  • @John - 你的表单是什么->创建?
  • @john Map 没有 id,所以它创建了一个新的..
  • @Dunhamzzz 感谢您的提示!

标签: cakephp cakephp-1.3


【解决方案1】:

正如@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'));
    }
    

    【讨论】:

    • id 已经设置在他的表单中(你可以在他的数据数组中看到)
    • 仍然应该使用 Oldskool 的方法,因为最终用户可以更改表单数据
    【解决方案3】:

    你应该使用更新:

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

    【讨论】:

    • 不,在这种情况下您不应该这样做。他正在更新一条记录。更新 all 可以防止发生某些蛋糕操作(例如更新修改的字段)
    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 2021-10-20
    • 2015-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多