Brieuc
Brieuc

Reputation: 4114

Doctrine : Class Table Inheritance : Add an existing object from parent table to extended table

Using the exemple provided by doctrine documentation

<?php
namespace MyProject\Model;

/**
 * @Entity
 * @InheritanceType("JOINED")
 * @DiscriminatorColumn(name="discr", type="string")
 * @DiscriminatorMap({"person" = "Person", "employee" = "Employee"})
 */
 class Person
{
    // ...
}

/** @Entity */
class Employee extends Person
{
    // ...
}

Assuming that i have an existing object Person. I wish to promote this Person as Employee. I can't find a way to do that. I tried to add a OneToOne relationship and create setPerson or setUser methods.

$employee = new Employee();
$employee->setRole('ROLE_EMPLOYEE');
$employee->setPerson($person);

OR

$employee = new Employee();
$employee->setRole('ROLE_EMPLOYEE');
$person->setEmployee($employee);

For sure i didn't manage to make this work and can't find another way to do it. The only way that could work is to delete the object person and create a new employee with previous person's data.

Any hints or solutions?

Upvotes: 1

Views: 169

Answers (1)

Michał Jędraszczyk
Michał Jędraszczyk

Reputation: 136

Doctrine dont allow to change types on the fly, why?:

if u create Person object its should be Person to the end, for example if employee will have some extra fields and u would downgrade it to Person, u lost Employee fields. Thats why u should create new object.

inheritance was created only to map OOP Inheritance to database, use it if u want some extra fields in child entity.

But if u still want to change discr u may use:

$em->getConnection()->exec( "UPDATE Person SET discr = 'employee' WHERE id = ".$entity->getId() );

Upvotes: 1

Related Questions