You need to check if the connection exists and then insert / update.
A. - Close the INSERT request in the try block and, in case of an error, create an update request. This will save all checks when the relationship does not exist ...
B. - Do all INSERT ON DUPLICATE UPDATE. This will do the same as in "A", but you do not need to worry about exceptions.
Definitely your second idea is completely wrong.
I would not create table keywords, since you only need the keyword itself ... then I would define my model_has_keyword as follows:
CREATE TABLE model_has_keyword ( model_id INT NOT NULL, keyword VARCHAR(50) NOT NULL, timesCount INT NOT NULL, roundCount INT NOT NULL, PRIMARY KEY (model_id,keyword) );
and update it as follows:
INSERT INTO model_has_keyword (model_id,keyword,timesCount,$myIntValue) VALUES ($model_id,$keyword,0,0) ON DUPLICATE KEY UPDATE timesCount=timesCount+1,roundCount=roundCount + $myIntValue
source share