php - MySQL delete and remove from many-to-many table in one transaction -
is possible delete association table (many-to-many) , insert same row in same transaction?
this association 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); when creating new image , inserting image, insert tag , insert image_tag in 1 transaction, works.
the problem occurs when want to update image , i:
- start transaction
- update image given $id
- call: delete image_tag imageid = $id
- check whether image_tag empty imageid = $id (and is)
- retrieve ids of new tags (some of them remains same)
- try insert image_tag ...but receive exception
exception:
cannot add or update child row: foreign key constraint fails (`mydatabase`.`image_tag`, constraint `fkimage_tag426448` foreign key (`imageid`) references `image` (`id`)) data:
original data: (194, 123), (194, 225), (194, 291) new data: (194, 123), (194, 225), (194, 65) source code (in 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 $this->db->query('delete image_tag imageid = %i', $img->getid()); // save tags , assign them image $tagids = $this->tagmanager->savetags($values->tags); $assoc = (new dao\imagetag())->setdb($this->db); //throw new \exception(implode(",", $tagids)); foreach ($tagids $tagid) { // exception throwed here (but after editation) $assoc->create($img->getid(), $tagid); }
don't try update image_tag invalid id? ..null, 0, -1 or else?
look code. suppose $img , $values->image not same, load $img when $values->image provided. however, try update image_tag every time.
Comments
Post a Comment