0

我正在使用 CakePHP v2.3.5。当我更新表格时

`users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(320) NOT NULL,
  `password` varchar(45) NOT NULL,
  `firstname` varchar(255) DEFAULT NULL,
  `lastname` varchar(255) DEFAULT NULL,
  `country` varchar(255) DEFAULT 'SG',
   PRIMARY KEY (`id`)
);

使用$this->User->save($this->request->data),它总是触发一个插入命令并抛出

"Integrity constraint violation: 1062 Duplicate entry '10' for key 'PRIMARY'"

request->data对象是:

array(
    'User' => array(
        'id' => '10',
        'firstname' => 'Someone',
        'lastname' => 'Surname',
    )
)

我现在使用的完整操作是:

public function addInfo() {
    if ($this->request->is('post')) {

        $this->User->create();
        $this->User->id=(int)$this->request->data['User']['id'];
        if ($this->User->save($this->request->data)) {

        }

    }
}

而模型中的 beforeSave 函数是:

公共函数 beforeSave($options = array()) {

   if (isset($this->data['User']['password'])) {
       $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
   }
   return true;

}

在用户对象中,这个 id=>false 对我来说看起来很可疑

object(User) { displayField => 'firstname' primaryKey => 'id' useDbConfig => 'default' useTable => 'users' id => false data => array( [最大深度达到] ) }

4

5 回答 5

2

在保存之前进行创建

$this->User->create();
$this->User->save($this->request->data); //with the id cast as integer

create用于重置模型,因此即使是更新,您也应该调用该函数作为预防措施。

于 2013-07-10T16:04:45.813 回答
0

在保存之前尝试设置 ID:

$this->User->id = useridhere
$this->Users->save($this->request->data);
于 2013-07-10T15:49:36.640 回答
0

我在这里遇到了同样的问题。我尝试了不同的配置(使用 save()、saveAll()、saveMany()、saveAssociated(),使用deep选项),后来我发现我的表有不同的主键(主字段名称不是“id ”)。将主字段名称添加到我的模型可以解决问题。

class SomeModel extends AppModel {

    public $primaryKey = "different_primary_field_name_for_id";

}
于 2014-09-26T13:18:32.523 回答
0

如果您想更新一个值,而不是创建一个新值,请确保您将主键字段传递到数据数组中:

$data = array('id' => 10, 'firstname' => 'Someone', 'lastname'=> 'Surname');
// This will update User with id 10

$this->User->save($data);
于 2013-07-10T15:45:52.143 回答
0

找到了原因。我碰巧在 Model 中调用了一个函数,getId并且 CakePHP 也getId用于检查行的存在,因此,在通过 id 检查时它总是得到否定结果,因此它触发了插入调用而不是更新调用。感谢大家的帮助。

于 2013-07-13T16:21:53.343 回答