我正在建立一个问答网站,我的问题、答案和评论都在同一个 posts
table 。但是他们的postType
是不同的。我可以通过此关联获得问题的答案和对答案的评论:
/**
* @OneToMany(targetEntity="Cms\Entity\Post", mappedBy="parent")
*/
private $answers;
/**
* @OneToMany(targetEntity="Cms\Entity\Post", mappedBy="parent")
*/
private $comments;
但我认为这不是正确的方法,因为如果我获取一个问题,答案和评论都只是答案。我必须为
postType = 1
这样的关系设置条件我怎样才能做到这一点?
最佳答案
您的架构无效。你应该有两个不同的对象来回答和评论,因为它们是两个不同的东西,即使它们共享一个共同的界面。
您应该创建两个实体,Answer
和 Comment
并与他们建立联系。因为它们几乎是一样的,你可以创建一个抽象类,AbstractContent
,它定义了所有必需的字段和访问器方法。 Doctrine 支持继承,因此最终的数据库模式将完全相同,但您的 OO 模型将是正确的。
/**
* @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;
您可以在其文档页面上阅读有关 Doctrine 中继承的更多信息:Inheritance Mapping
关于 Doctrine ORM 条件关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6634357/