I am trying to insert multiple or single tags to a book, I have 3 tables such as books(books record), tags(tags record), books_tag(relation for books and tags), from this Should I store tags in a text field or in a separate table? question I got this idea.
I am first inserting books along with tags, then I am getting the last added ID of the book and trying to insert into books_tag table along with tag ID. My code working perfectly for newly adding tags (which is not existed on tags table) for a book, but if I try to insert existed tag, it is always insert tag ID as 0 (should be existed tag ID from tags table) on books_tag table, Here is my code
public function addTag($tags, $book_id)
{
// Loop tags to insert
foreach ($tags as $tag) {
// insert tags if not existed
$this->db->query('INSERT INTO tags (tag) VALUES (:tag) ON DUPLICATE KEY UPDATE tag = :tag');
// Bind values
$this->db->bind(':tag', $tag);
// Execute query
$this->db->execute();
// Get lsat id
$last_tag_id = $this->db->lastId();
$this->db->query('INSERT INTO books_tag (book_id, tag_id) VALUES (:book_id, :tag_id)');
// Add tag to books
$this->db->bind(':book_id', $book_id);
$this->db->bind('tag_id', $last_tag_id);
// Execute query
$this->db->execute();
}
}