Skip to content
Advertisement

Can I use the same table to represent different Entities in Symfony?

I am migrating an old PHP project to Symfony. I am trying to create the entities based on the existing database schema which I can not change. I am facing a problem :

There is a table that would represent two different entities. Basically, there is a boolean (a tinyint(1)), if the boolean is false, then the row of the table is representing a cart. If the boolean is true, then the row is representing an order.

Is it possible for Doctrine to make the distinction between these and to fetch those entities accordingly ? The solution I was willing to implement was creating several entities and overwrite the find() and findAll() methods in these entities’ repositories. Is there another way to achieve that ?

Advertisement

Answer

This is what doctrine call Inheritance Mapping.

So you’ll have one Cart entity and one Order entity extended it.

/**
 * @ORMTable()
 * @ORMEntity(repositoryClass="AppRepositoryCartRepository")
 * @ORMInheritanceType(value="SINGLE_TABLE")
 * @ORMDiscriminatorColumn(name="is_order", columnDefinition="BOOL DEFAULT FALSE")
 * @ORMDiscriminatorMap(
 *     value={
 *      CART::IS_CART=Cart::class,
 *      CART::IS_ORDER=Order::class
 *     }
 * )
 */
class Cart {
   const IS_CART = FALSE;
   const IS_ORDER = TRUE;
   ... // Entity field, getters, setters, functions...
}

Then your Order Entity.

/**
 * @ORMEntity(repositoryClass=OrderRepository::class)
 */
class Order extends Cart {...}

There is maybe some mistake in this code I didn’t test it but it should be ok.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement