在保存时更新实体而不是在插入时更新实体

Update entity on save rather than insert

在我的代码中,我试图在调用控制器函数时创建一个锁定实体。创建新实体后,我将其保存在数据库中。一旦控制器功能完成其其余逻辑,我就会在 return 重定向之前更新锁定实体。但是,当我更新实体然后再次保存时,它总是会插入一个新的数据库行而不是更新现有实体。

到目前为止我已经尝试过的事情。

这两种方法都应更新 isNew() 以通知 save() 更新条目而不是插入新条目,但是我总是将新行添加到数据库中。

这是相关代码。

这是我的控制器函数内部的逻辑

//Inside of edit function of controller

$editLockTable = TableRegistry::get('TableLocks');
$editLock = newEntity($userId, $postId);
$editLock->lock();
if(!$editLockTable->save($editLock)){
    Throw new \Exception("Error with saving lock");
}
.
. // Some other controller function code
.
$editLock->unlock();
$editLock->isNew(false);
if(!editLockTable->save($editLock)){
     Throw new \Exception("Error with saving unlock");
}
//return redirect

这是我实体中的逻辑class

//Inside of Entity class for EditLock

public function lock($userId, $postId){
    $this->user_id = $userId;
    $this->post_id = $postId;
    $this->start_time = Time::now();
    $this->is_locked = true;
    $this->expire_time = Time::now()->modify('+10 minutes');
}

public function unlock(){
    $this->end_time = Time::now();
    $this->is_locked = false;

edit_lockstable定义

CREATE TABLE 'edit_locks' (
     'id' int(11) NOT NULL AUTO_INCREMENT,
     'post_id' int(11) NOT NULL,
     'user_id' int(11) NOT NULL,
     'is_locked' tinyint(1) DEFAULT '0',
     'start_time' datetime DEFAULT '0000-00-00 00:00:00',
     'end_time' datetime DEFAULT '0000-00-00 00:00:00',
     'expires_time' datetime DEFAULT '0000-00-00 00:00:00',
     'renews' int(11) DEFAULT 0,
     PRIMARY KEY ('id'),
     KEY 'fk_post_id' ('post_id'),
     CONSTRAINT 'fk_post_id' FOREIGN KEY ('post_id') REFERENCES 'posts'('id')
     ENGINE=InnoDB DEFAULT CHARSET=latin1
)

控制器功能完成后我在数据库中得到了什么

id|post_id|user_id|is_locked|start_time|end_time|expires_time|renews
1 | 999 | 32 | 1 | 2017-09-14 ... | 0000-00-00 ... | 2017-09-14 ... | 0
2 | 999 | 32 | 0 | 2017-09-14 ... | 2017-09-14 ... | 2017-09-14 ... | 0

控制器功能完成后我想要在数据库中得到什么

id|post_id|user_id|is_locked|start_time|end_time|expires_time|renews
1 | 999 | 32 | 0 | 2017-09-14 ... | 2017-09-14 ... | 2017-09-14 ... | 0

is_locked 和 end_time 都更新了,而不是新行

你的主键被列为 ID,你没有在任何看起来不像的地方设置它。如果您的主键不匹配,您将无法更新记录。为什么不做类似的事情。

$editLock = editLockTable->findByUserIdAndPostId($userId, $postId);
if($editLock == null) { $editLock = newEntity($userId, $postId); }

更好的是,您还可以进行 findOrCreate 调用,这样您就可以在一次调用中处理这两种情况。如果找不到记录,findOrCreate 将创建具有指定条件的实体。