3

I have a mapped superclass AbstractQuestion with single-table-inheritance.

/**
 * @ORM\Entity
 * @ORM\MappedSuperclass
 * @ORM\Table(name="Question")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="dtype", type="string")
 * @ORM\DiscriminatorMap({
 *  "simple":   "SimpleQuestion",
 *  "dropdown": "DropdownQuestion"
 * })
 */
abstract class AbstractQuestion

SimpleQuestion and DropdownQuestion inherit from this superclass.

/**
 * Class SimpleQuestion.
 * @ORM\Entity()
 */
class SimpleQuestion extends AbstractQuestion

I want to modify an existing SimpleQuestion and make it a DropdownQuestion.

When saving a question, I deserialise and merge the question, which contains an ID and the 'dtype' and other properties.

$dquestion = $this->serial->fromJson($request->getContent(), AbstractQuestion::class);
$question = $this->em->merge($dquestion);
$this->em->flush();

So I submit something like:

{ id: 12, dtype: 'dropdown', 'text': 'What is my favourite animal?'}

After the deserialisation, $dquestion is a DropdownQuestion object as I desired, but after the merge $question is a SimpleQuestion object as it was in the database previously, so any unique properties of DropdownQuestion are lost and the question is saved as a SimpleQuestion. Is there any way to work around this?

darkbluesun
  • 817
  • 8
  • 15

1 Answers1

4

You will first have to delete the existing record (SimpleQuestion) and then insert the new record (DropdownQuestion). Type casting is not supported in Doctrine 2.


Note.
You can probably change the discriminator column with a pure SQL query, but this is absolutely not recommended and will for sure give you problems...

Check also the answers here and here since they might be interesting for you.

Community
  • 1
  • 1
Wilt
  • 41,477
  • 12
  • 152
  • 203
  • 1
    Thanks. Disappointing, but true. I ended up in this situation because I converted a serialized object stored in a long text into an entity. Otherwise I guess I wouldn't have considered changing the question type. Thanks. – darkbluesun Jan 14 '16 at 19:32