简体   繁体   English

在Doctrine 2中的多个实体上的标签

[英]Tags on multiple entities in Doctrine 2

I'm trying to create a simple tagging system with Doctrine, but i'm not sure how to build the entity relationships. 我正在尝试使用Doctrine创建一个简单的标签系统,但是我不确定如何建立实体关系。 A User that can have multiple Tag would be a simple ManyToMany association, but what happens when i have two or more entities that can be tagged? 可以具有多个标签的用户将是一个简单的ManyToMany关联,但是当我有两个或多个可以进行标签的实体时会发生什么?

I have three entities: User, Group and Application. 我有三个实体:用户,组和应用程序。 All three entities can be tagged. 可以标记所有三个实体。 How can i relate those three with the Tag entity? 如何将这三个与Tag实体相关联?

You should map Tag entity in User, Group and Application entity, if you are using annotations then the code in each of mentioned entities should look similar to this: 您应该在用户,组和应用程序实体中映射Tag实体,如果您使用的是注释,则每个提到的实体中的代码应类似于以下内容:

/**
 * @ORM\Table(name="class_name")
 * @ORM\Entity
 */
class ClassName {
    // Definition of other attributes skipped

    /**
     * @ORM\ManyToMany(targetEntity="Tag")
     */
    private $tags;

    public function __construct(){
         $this->tags = new ArrayCollection();
    }

    // Definition of other methods skipped

    public function getTags(){
        return $this->tags;
    }

    public function setTags($tags){
        $this->tags = $tags;
    }

    public function addTag(Tag $tag){
        $this->tags->add($tag);
    }

    public function removeTag(Tag $tag){
        $this->tags->remove($tag);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM