在symfony2中的多个其他实体中使用实体 [英] use entity in multiple other entities in symfony2

查看:44
本文介绍了在symfony2中的多个其他实体中使用实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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)

我有一个名为CustomVar的实体

That i have an entity called CustomVar

我的项目有项目,类别,产品.

My project has projects, categories, products.

我希望我的项目中保存有customvars(onetomany),我的产品也要包含customvars(onetomany):

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?

推荐答案

所以您希望CustomVar与产品和项目相关?

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;
}

如果您的产品和项目相关,则现在可以执行$ product-> getProject()-> getCustomVars()以及$ product-> getCustomVars()并使用返回的ArrayCollections.

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).

这篇关于在symfony2中的多个其他实体中使用实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆