Vous pouvez créer un déclencheur qui change la valeur de NEW.slug avant de l'insérer.
drop trigger if exists changeSlug;
delimiter |
CREATE TRIGGER changeSlug BEFORE INSERT ON slugs
FOR EACH ROW BEGIN
declare original_slug varchar(255);
declare slug_counter int;
set original_slug = new.slug;
set slug_counter = 1;
while exists (select true from slugs where slug = new.slug) do
set new.slug = concat(original_slug, '-', slug_counter);
set slug_counter = slug_counter + 1;
end while;
END;
|
delimiter ;
Et voici les résultats
mysql> insert into slugs values ("dude");
Query OK, 1 row affected (0.00 sec)
mysql> insert into slugs values ("dude");
Query OK, 1 row affected (0.00 sec)
mysql> insert into slugs values ("dude");
Query OK, 1 row affected (0.00 sec)
mysql> select * from slugs;
+--------+
| slug |
+--------+
| dude |
| dude-1 |
| dude-2 |
+--------+
3 rows in set (0.00 sec)