usar entidad en muchas otras entidades en symfony2

I am new to symfony2

How do i go about re-using an entity in multiple other entities?

Say, for example (this is actually the case)

That i have an entity called CustomVar

My project has projects, categories, products.

I want my project to hold customvars (onetomany) and my product to also hold customvars (onetomany):

project 1:n customvar

product 1:n customvar

So that when accessing my product, I have access to the custom vars on project level, alswell as those on product level.

I am assuming these would both use the same object, but how do i properly annotate and use this?

preguntado el 04 de julio de 12 a las 10:07

1 Respuestas

So you want CustomVar to relate to both Product and Project?

class CustomVar {

     * @ORM\ManyToOne(targetEntity="Project", inversedBy="customVars")
     * @ORM\JoinColumn(name="project_id", referencedColumnName="id", nullable=true)
    private $project;

     * @ORM\ManyToOne(targetEntity="Product", inversedBy="customVars")
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id", nullable=true)
    private $product;

In our Project (or product), you would have this code:

class Project {

     * @ORM\OneToMany(targetEntity="CustomVar", mappedBy="project")
    private $customVars;

If your product and project are related, you could now do $product->getProject()->getCustomVars() as well as $product->getCustomVars() and works with the returned ArrayCollections.

If you want it to only relate to one of the two objects, you could have the setters check if another relation is set (by testing project and product variables) and then handling it your way (throwing exception, silently doing nothing and so on).

Respondido 04 Jul 12, 12:07

product is manytoone to category and category is manytoone to project your example, is pretty much exactly what i have right now. but the thing i was wondering about was: one particular customvar is attached to either a project, or a product, not both, will this cause any issues, is there anything i should mind ? (this is what your saying in your second paragraph no? if so, could u explain a little better for me ?) - sam janssens

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.