I have following table (type, id, title).
When new object is created and type=1 id should be 1, next object with type=1 id=2... But when I create object with type=2 id should be 1.
How can I do it with Doctrine2 and Symfony2?
Like other have said, Doctrine 2 does not do this out of the box. The common practice is to make the ID field auto increment and a primary key in which case this is not possible. Primary keys must be unique.
With that said, a solution could be to use the entity manage to find the maximum value of ID where the type is the selected type and incrementing that value by 1.
For example:
// Retrieve the current maximum ID for the selected type
$id = $em->createQuery("SELECT MAX(e.id) AS id FROM Entities\entity e WHERE e.type = ?1")
->setParameter(1, $type)
->getSingleScalarResult();
// Set your current entity's ID
$entity->setId(++$id);
// Save the entity
...
As my comments above indicate, I don't think there's direct support for what you're trying to do out of the box. However, I think you should be able to approximate it with class table inheritance, where each of your type
categories is its own entity that shares common data on the class table and keeps track of its own indexing.
Using MAX(id)
is not a very best solution as it might cause a few problems. What happen if you delete the newest record in given category and then add a new one? It will have the very same ID as previous had.
type
, id
) are not very well handled by Doctrine so far, so I suggest to create a classical primary key: integer, auto-increment key (at least for Doctrine's use). In addition you can always have a unique index on type
and type_id
columns and use it whenever you want.Create your own implementation for auto-increment of type_id
column:
type_id
is associated with Type you could store additional column in type
table: next_auto_increment
, which stores a value that will be used for next record.Whenever you create a new record in your table simply select value for it's type_id
from type
table:
$type = ...;
$entity = new Entity();
$entity->setType($type);
$entity->setTypeId($type->getNextAutoIncrement());
// btw: typeId is not a very best name
$em->persist($entity);
You will also need a trigger in your database to increment a value of next_auto_increment
every time you insert a record (MySQL example):
DELIMITER $$
CREATE TRIGGER increment_ai AFTER insert ON entity_table FOR EACH ROW BEGIN
UPDATE type_table
SET next_auto_increment = next_auto_increment + 1
WHERE id = NEW.type;
END$$
DELIMITER ;