Dynamic Target entity Doctrine 2 and Symfony 2

Viewed 1507

I want dynamic entity mapping on one entity which will be used by other entities. For example, I have a File entity, which will store MIME type, mapping key, name etc, also an entity_id which will contain the id to the entity it belongs to. The mapping key will determine the class as this file entity will be many-to-many. So the targetEntity for File entity isn't fixed. How to achieve that?

File Entity

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * File
 *
 * @ORM\Entity
 */
class File {
    //.... Other mapping properties

    /**
     * @ORM\ManyToOne(targetEntity="SuperClass", inversedBy="files")
     * @ORM\JoinColumn(name="entity_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $entity;
}

Product Entity

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Product
 *
 * @ORM\Entity
 */
class Product extends SuperClass {
    //.... Other mapping properties

    /**
     * @ORM\OneToMany(targetEntity="File", mappedBy="entity")
     */
    protected $files;
}

But I have many other entities similar to Product and how do I make sure that when I call getFiles(), I get the files of the respective entity. I think it may work like this anyway, but is this the right way, or is there a better way?

2 Answers
Related