I have 2 mysql tables and I want that:
1) when I delete an article, the associated tags to be automatically deleted
2) when I add/delete a tag, the “hasTags” field from the articles to be auto updated (0 – for 0 tags, 1 – for 1+ tags).
For 1 – I used a foreign key and it works
ALTER TABLE `articles`
ADD CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`id`) REFERENCES `tags` (`id`) ON DELETE CASCADE;
I don’t know how to do for the second part. It is possible?
The tables are
articles == id | title | content | hasTags
tags == id | articleId | tagname
Thanks!
For part 2 you can either do this on your application code, in the part where you also add/delete a tag.
Update, I would suggest making
hastagsa reference counter, that way you avoid the problem @James mentioned.Or you can create 3 triggers: