I’m struggling with the following problem concerning primary ids within mysql:
I got an entity Client and an entity Purchase, where one client has zero to many purchases and a purchase has exactly one client.
When I create a purchase, I want to assign my own primary key which refers to the client and a ongoing number, like abc1 for the first purchase for client abc. The purchase table could look like this:
id | client
abc1 | abc
abc2 | abc
def1 | def
abc3 | abc
def2 | def
My application uses symfony2 with doctrine2, so I searched and thought for a while and then implemented a createPurchase method in the PurchaseRepository which reads the amount of purchases for a specific client, adds one and returns the created Purchase with the id already added:
public function createPurchase($client){
$amount = $this->getAmountForClient($client) + 1;
$id= $client->getId() . $amount ;
return new Purchase($id);
}
There are some problems with this solution:
- Adding more than one entity without flushing results in dublicated primary id
- Running the script at the same time might cause dublicated primary ids
Is there another way I’m not aware of right now which might solve my problems? Am I doing it completly wrong? Any help is appreciated!
This is why the AUTO_INCREMENT feature exists, so concurrent transactions can generate unique primary key values.
To do this with your own code, you would have to use
LOCK TABLES Purchase WRITEbefore callinggetAmountForClient(), to prevent the race condition with other transactions that causes the duplicate key errors.No one does this. They forego the idea of custom primary keys as you have described, and just use AUTO_INCREMENT instead.