Можете да създадете задействане което променя стойността на NEW.slug преди да го вмъкне.
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 ;
И това ще бъдат резултатите
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)