Alexander Yakutskiy
Alexander Yakutskiy

Reputation: 315

Symfony2 and Doctrine: complex relations

In my project I have entities News, Articles and Comments. Users can add comments both to articles and news. Each user can add a few comments for each article or new. I want have single Comments entity with composite key for relationships with News and Articles like

subj_type (news or articles) + subj_id (id of new or article)

Can I organize relationships by this way? Or I must organize two different Comments entities (like NewsComments and ArticlesComments)?

Upvotes: 0

Views: 171

Answers (1)

viblizn
viblizn

Reputation: 132

You can use Inheritance Mapping and organize three Entities - Comments,NewsComments and ArticleComments by using Single Table Inheritance:

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="type", type="string")
 * @DiscriminatorMap({"news" = "NewsComments", "article" = "ArticleComments"})
 */
class Comments
{
    protected $type;
    protected $doc_id;
    // ...
}

/**
 * @Entity
 */
class News extends ArticleComments
{
    // ...
}

/**
 * @Entity
 */
class News extends NewsComments
{
    // ...
}

NewsComments and ArticleComments entities will contain (for exmaple) doc_id. In doc_id you will store News or Article Id. And when will you get Comments for News through NewsComments repository, your will get Comments for News only.

Doctrine Inheritance Mapping

Upvotes: 1

Related Questions