Your schema is invalid. You schould have two different objects for answers and comments as they are two different things, even if they share a common interface.
You should create two entities, Answer
and Comment
and create assocations to them. As they are almost the same thing you could create an abstract class, AbstractContent
, that defines all required fields and accessor methods. Doctrine supports inheritance so the final database schema will be exactly the same, but your OO model will be correct.
/**
* @MappedSuperclass
* @InheritanceType("SINGLE_TABLE")
* @DiscriminatorColumn(type = "string", name = "discriminator")
* @DiscriminatorMap({ "answer" = "Answer", "comment" = "Comment" })
*/
abstract class AbstractContent {
/** @Column(type = "integer") @Id @GeneratedValue("AUTO") */
protected $id;
/** @Column(type="text") */
protected $content;
/** @Column(type = "datetime", name = "created_at") */
protected $createdAt;
public function __construct() {
$this->createdAt = new \DateTime();
}
}
/** @Entity */
class Answer extends AbstractContent { }
/** @Entity */
class Comment extends AbstractContent { }
/**
* @OneToMany(targetEntity="Cms\Entity\Answer", mappedBy="parent")
*/
private $answers;
/**
* @OneToMany(targetEntity="Cms\Entity\Comment", mappedBy="parent")
*/
private $comments;
You can read more about inheritance in Doctrine on its documentation pages: Inheritance Mapping
@Entity
tag needs to be included into super class or it will report error "Its not supported to define inheritance information on a mapped superclass". – Siwei Dec 29 '14 at 04:56