Potresti creare un trigger che cambia il valore di NEW.slug prima di inserirlo.
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 ;
E questo sarebbe il risultato
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)