Ariyan
Ariyan

Reputation: 15148

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?

Upvotes: 0

Views: 35

Answers (1)

Crozin
Crozin

Reputation: 44396

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

Upvotes: 1

Related Questions