I want to make an insert with a calculated field in doctrine. If I would do it with SQL it would look like:
INSERT INTO "TableX"
( "ID_Special",
"Name"
)
VALUES ( (select MAX(ID_Special) + 1 from "TableX"),
"blabla"
)
“ID_Special” should be an autoinc-Value without beeing unique. So there are other INSERT’s made on “TableX” that insert an already existing “ID_Special”.
Now I am going the following way:
$qb = $em->createQueryBuilder();
$qb->select('MAX(r.ID_Special)')->from('TableX', 'r');
$nextIDSpecial = $qb->getQuery()->getSingleScalarResult();
...
$dataset = new TableX();
$dataset->setIDSpecial($nextIDSpecial);
$dataset->setName('blabla');
$em->persist($dataset);
$em->flush();
But this might run into problems, if I have multiuser access.
Is there a way to create the first shown SQL-statement with DQL?
Or is there a way to make my second approach atomar?
The best way I found until now: I created a table named “IDSpecialGenerator” with only one column of type integer, pk, not null and autoinc. Everytime I want to insert a dataset into “TableX” with a new “ID_Special” I first have to make an insert into “IDSpecialGenerator”. So my database makes the calculation, I have no problems with multiuseraccess and I not have to use native SQL.