我正在建立一个问答网站,我的问题、答案和评论都在同一个网站上posts
桌子。但他们的postType
是不同的。我可以通过该协会获得问题的答案和答案的评论:
/**
* @OneToMany(targetEntity="Cms\Entity\Post", mappedBy="parent")
*/
private $answers;
/**
* @OneToMany(targetEntity="Cms\Entity\Post", mappedBy="parent")
*/
private $comments;
但我认为这不是正确的方法,因为如果我获取一个问题,答案和评论都会充满答案。我必须为关系设置一个条件,例如postType = 1
我怎样才能做到这一点?
您的架构无效。您应该有两个不同的对象用于答案和评论,因为它们是两个不同的东西,即使它们共享一个公共接口。
您应该创建两个实体,Answer
and 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 的文档页面上阅读有关继承的更多信息:继承映射 http://www.doctrine-project.org/docs/orm/2.0/en/reference/inheritance-mapping.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)