[英]how to get id of unique column
$tags = array('strawberries','blueberries','food','strawberries')
function hashTagInsert($tags)
{
/// commit this as a transaction
$lastInsertId = $this->db->lastId(); // last insert id of article
foreach ($tags as $val)
{
$sql = 'INSERT INTO tags (tag, added) VALUES (:tag, NOW()) ON DUPLICATE KEY UPDATE occurrence = occurrence + 1';
$this->db->boolQuery($sql, array(':tag' => $val));
$sql2 = 'INSERT INTO tags_refs (article_id, tag_id) VALUES (:lastInsertId, LAST_INSERT_ID())';
$this->db->boolQuery($sql2, array(':lastInsertId' => $lastInsertId));
}
}
我寫了這樣的腳本來照顧它。 而且有效。 不幸的是,由於存在唯一的列,因此重復性有點問題。
如果存在重復性,則將原點標記保留為原樣,並且我不知道它具有的ID。 在那之后的另一個表格中,我為不存在的最后一個插入標記獲取了新的參考。
標簽存在,但引用錯誤。
在第一個處理腳本之后,數據庫看起來像這樣:
CREATE TABLE `tags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tag` varchar(100) NOT NULL,
`occurrence` int(11) NOT NULL,
`added` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `tag` (`tag`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `tags` (`id`, `tag`, `occurrence`, `added`) VALUES
(18, 'boobs', 1, '2015-05-29 16:46:44'),
(20, 'food', 0, '2015-05-29 16:46:44'),
(19, 'blueberries', 0, '2015-05-29 16:46:44');
and the reference one:
DROP TABLE IF EXISTS `tags_refs`;
CREATE TABLE `tags_refs` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`article_id` int(11) NOT NULL,
`tag_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO `tags_refs` (`id`, `article_id`, `tag_id`) VALUES
(24, 31, 18),
(25, 31, 19),
(26, 31, 20),
(27, 31, 26);
-- 2015-05-29 14:49:55
function hashTagInsert($tags)
{
/// commit this as a transaction
$lastInsertId = $this->db->lastId();
foreach ($tags as $val)
{
$sql = 'INSERT INTO tags (tag, added) VALUES (:tag, NOW()) ON DUPLICATE KEY UPDATE occurrence = occurrence + 1, last_article_id = :lastInsertId';
$stmt = $this->db->boolQuery($sql, array(':tag' => $val,
':lastInsertId' => $lastInsertId));
if(!$stmt)
{
$sql3 = 'SELECT id FROM tags WHERE tag = :tag';
$existingTagId = $this->db->queryFetch($sql3, array(':tag' => $val));
}
$tagId = (isset($existingTagId)? $existingTagId : $this->db->lastId());
$sql2 = 'INSERT INTO tags_refs (article_id, tag_id) VALUES (:lastInsertId, :tagId)';
$this->db->boolQuery($sql2, array(':lastInsertId' => $lastInsertId,
':tagId' => $tagId));
unset($existingTagId);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.