Altherius
Altherius

Reputation: 784

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 ?

Upvotes: 2

Views: 354

Answers (1)

Vincent PHILIPPE
Vincent PHILIPPE

Reputation: 1191

This is what doctrine call Inheritance Mapping.

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

/**
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="App\Repository\CartRepository")
 * @ORM\InheritanceType(value="SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="is_order", columnDefinition="BOOL DEFAULT FALSE")
 * @ORM\DiscriminatorMap(
 *     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.

/**
 * @ORM\Entity(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.

Upvotes: 1

Related Questions