有什么优雅的解决方案如何插入多对多表?
我得到了这些表:
- 标签 - 包含标签名称和 id(Tag_ID,标签)
- TagReview - 标签和评论之间的链接表(Review_ID,Tag_ID)
- 评论 - 保存评论。 (Review_ID,内容,...)
目前,我在添加或编辑评论时进行了插入。 在我的 Tag 表类中,扩展自 Zend_DB_Table... 插入在某些情况下有效,但随后失败并出现 SQL 错误“ SQLSTATE[23000]:完整性约束违规:1452”
public function insertTags($reviewId, $tagList) {
$reviewTag = new Application_Model_DbTable_ReviewTag;
$tags = explode(self::SEPERATE, $tagList);
foreach ($tags as $tag) {
$tag = trim($tag);
$tagRow = $this->fetchRow(array('tag = ?' => $tag));
if ($tagRow == null) {
$tagId = $this->insert(array(
'tag' => trim($tag)
));
$reviewTag->insert(array(
'Tag_ID' => $tagId,
'Review_ID' => $reviewId,
));
}
}
}
I got these tables:
- Tag - contains the tag names and id (Tag_ID, tag)
- TagReview - linking table between tags and reviews (Review_ID, Tag_ID)
- Review - holds reviews. (Review_ID, content, ...)
Currently i have made an insertions when review is added or edited.
In my Tag table class extends from Zend_DB_Table...
Insertion worked for some cases but then failed with sql error " SQLSTATE[23000]: Integrity constraint violation: 1452"
public function insertTags($reviewId, $tagList) {
$reviewTag = new Application_Model_DbTable_ReviewTag;
$tags = explode(self::SEPERATE, $tagList);
foreach ($tags as $tag) {
$tag = trim($tag);
$tagRow = $this->fetchRow(array('tag = ?' => $tag));
if ($tagRow == null) {
$tagId = $this->insert(array(
'tag' => trim($tag)
));
$reviewTag->insert(array(
'Tag_ID' => $tagId,
'Review_ID' => $reviewId,
));
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所以问题是:
如果我必须在没有堆栈跟踪的情况下进行猜测,我会说以下行是问题所在:
我假设您对标签表有一个唯一的约束,以确保不会将重复的标签添加到表中。
问题是这一行不应该是插入,它应该是 getTagIDByTag,如果失败,则插入。
所以,
<代码>
<代码>
so the problem is a:
If i had to take a guess without a stack trace, I would say the following line is the problem:
I assume you have a unique constraint on your tag table to make sure duplicate tags aren't added to the table.
The issue is that this line shouldn't be a insert, it should be a getTagIDByTag and failing that, insert.
SO,
我已经通过这段代码解决了我的解决方案。如果在编辑时删除或添加了标签,还可以处理问题。
I have solved my solution by this code. Also handles the problem if on edit the tags has been removed or added.