简体   繁体   中英

Entity that has two semantical types in symfony2

I need for an entity in my project to have two semantical types; Assume Post entity that can be two type of post: "text" post & "link" post.
So my post entity is something like this:

Class Post{
    private $id;
    private $type;
    private $text=nul;
    private $link=null;

    ...
}

Now a post only can have one of text or link fields based on the type field and the other should be Null
How can I implement such a thing with Symfony2 / Doctrine / Forms ?
Should I split it to two entities or symfony can manage such a situation?

You could use inheritance in this case. Declare an abstract class with properties common to both LinkPost and TextPost :

@Entity
@InheritanceType("SINGLE_TABLE")
@DiscriminatorColumn(name="discriminator", type="string")
@DiscriminatorMap({"text"="TextPost", "link"="LinkPost"})
abstract class Post {
    @Id @GeneratedValue @Column
    private $id;

    @ManyToOne(...)
    private $author;
}

@Entity
class TextPost extends AbstractPost {
    @Column
    private $content;
}

@Entity
class LinkPost extends AbstractPost {
    @Column
    private $url;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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