原则ORM条件协会 [英] Doctrine ORM Conditional Association

查看:223
本文介绍了原则ORM条件协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个Q&A的网站,我的问题,答案和评论是在同一个帖子表。但他们的 postType 是不同的。我可以得到一个问题的答案和评论与这个协会的答案:

i'm building a Q&A site and my questions, answers and comments are on the same posts table. But their postType is different. I can get answers for a question and comments for an answer with this association:

/**
 * @OneToMany(targetEntity="Cms\Entity\Post", mappedBy="parent")
 */
private $answers;

/**
 * @OneToMany(targetEntity="Cms\Entity\Post", mappedBy="parent")
 */
private $comments;

但我认为这不是正确的方法,因为如果我提出了一个问题,评论只填写答案。我必须设置一个关系的条件,如 postType = 1

But i think this is not the correct way to do this because if i fetch a question both answers and comments are filling with just answers. I have to set a condition for relation like postType = 1

我该怎么做?

推荐答案

您的模式无效。即使他们有共同的界面,你也可以有两个不同的对象来获得答案和评论,因为它们是两个不同的东西。

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.

你应该创建两个实体,回答评论并创建关联。由于它们几乎相同,您可以创建一个抽象类, AbstractContent ,定义所有必需的字段和访问器方法。 Doctrine支持继承,所以最终的数据库模式将完全一样,但是你的OO模型是正确的。

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;

您可以在其文档页面上了解有关Doctrine中继承的更多信息:继承地图

You can read more about inheritance in Doctrine on its documentation pages: Inheritance Mapping

这篇关于原则ORM条件协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆