Larval change Auto-increment from Id to id-Year

Asked

Viewed 33 times

-2

I wonder if it is possible in washable to change the auto-increment from "Id" to "id-Year"

Example:

When we have a user with Id:2 I wish it had id: 2-2021

If possible, how can I make this amendment ?

1 answer

0

Assuming you use mysql 5.7+, and Laravel 5.3+.

Although I don’t understand the usability of this you ask (because an autoincrement column theoretically has to be unique, regardless of the year) you should keep in mind that to make you need an autoincrement column, either automated in a database or in the code (PHP/Laravel).

I don’t feel like altering the spine id (this column can have the name you want, this is only convention), instead in the migrations of the add a column as:

...
$table->integer('uid')->storedAs('CONCAT(id, '-',  YEAR(CURDATE()))')->unique();
...

In this case I named this column as uid, however you can give whatever you want.

If you only use Mysql 5.7+:

You can do this right on mysql:

ALTER TABLE <NOME TABELA> ADD uid INTEGER AS (CONCAT(id, '-', YEAR(CURDATE()))) STORED

Then for a search, you can just:

SELECT * FROM <NOME TABELA> WHERE uid = CONCAT(<ID>, '-', YEAR(CURDATE()))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.