且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在symfony2中的多个其他实体中使用实体

更新时间:2022-11-04 20:41:45

所以您希望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).