MySQL 在一个事务中从多对多 table 中删除和移除

MySQL delete and remove from many-to-many table in one transaction

是否可以从关联 table(多对多)中删除并在同一事务中向其插入同一行?

这是我的协会table:

CREATE TABLE image_tag (
  imageid bigint(19) NOT NULL, 
  tagid   bigint(19) NOT NULL, 
  PRIMARY KEY (imageid, tagid));
ALTER TABLE image_tag ADD INDEX FKimage_tag587679 (tagid), ADD CONSTRAINT  FKimage_tag587679 FOREIGN KEY (tagid) REFERENCES tag (id);
ALTER TABLE image_tag ADD INDEX FKimage_tag426448 (imageid), ADD CONSTRAINT FKimage_tag426448 FOREIGN KEY (imageid) REFERENCES image (id);

当我创建一个新图像并将其插入图像、插入标签和插入 image_tag 时,一切正常。

当我想更新图片时出现问题,我:

异常:

Cannot add or update a child row: a foreign key constraint fails (`mydatabase`.`image_tag`, CONSTRAINT `FKimage_tag426448` FOREIGN KEY  (`imageid`) REFERENCES `image` (`id`))  

数据:

Original data: (194, 123), (194, 225), (194, 291)
New data: (194, 123), (194, 225), (194, 65)

源代码(在PHP):

if ($editation) {
  if ($values->image->isOk()) {
    $url = $img->load($values->id)->getUrl();
    $values->image->move($this->wwwDir . "/" . $url);
  } else {
    $url = null;
  }      
  $img->update($values->name, $values->descr, $url, null, $featured);
} else {
  $uname = $img->createUniqueName($values->name);
  $url = ImageManager::PATH . "/" . $uname . ".svg";
  $values->image->move($this->wwwDir . "/" . $url);
  $img->create($userId, $values->name, $url, $values->descr, null, $featured);      
}

// Delete old image-tag associations if any
$this->db->query('DELETE FROM image_tag WHERE imageid = %i', $img->getId());

// Save tags and assign them to image
$tagIds = $this->tagManager->saveTags($values->tags);
$assoc = (new Dao\ImageTag())->setDb($this->db);
//throw new \Exception(implode(",", $tagIds));
foreach ($tagIds as $tagId) {     
  // EXCEPTION IS THROWED HERE (but only after editation)
  $assoc->create($img->getId(), $tagId);      
}

您不尝试用无效 ID 更新您的 image_tag 吗? ..null、0、-1 或其他什么?

查看您的代码。我想 $img 和 $values->image 不一样,但只有在提供 $values->image 时才加载 $img。但是,您每次都尝试更新 image_tag。