8

I have comments and articles, both are votable.

So, basically I've three entities, Article, Comment and Vote.

After some reading on Single Table Inheritance in Doctrine2 reference manual, it seems that it's what I need, because my Vote remains the same over Article or Comment.

Over the ORM view, here is how I see my Vote table:

id | resource_id | resource_type | weight |

I guess the resource_type should be the "discriminator" column, but I don't really understand how to implement this within my entity.

What I'm trying to do is to avoid to have to Vote table for each of my entities since the vote entity remains the same for the both, except the "resource_type", so I'm trying to find a way within Doctrine2 to be able to have only one Vote entity to work with.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
JohnT
  • 467
  • 6
  • 14
  • I don't fully understand what you are trying to achieve. Can you please explain a little more about how your domain should function, I'm thinking inheritance might not be the go here... – Cobby Apr 29 '11 at 01:37
  • @Cobby, I edited my question, I hope it's clearer – JohnT Apr 29 '11 at 08:36
  • @Cobby, you may be right, I'm wondering if it's the proper way to implement such system.` – JohnT Apr 29 '11 at 08:37
  • I still don't get when your objective is. IMO, I think you should have separate entities and separate tables even though they are the same. Write a MappedSuperclass containing all the logic, then empty Vote entities. Could you please explain your system? – Cobby Apr 30 '11 at 21:43

2 Answers2

8

Based on the example from the docs:

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="resource_type", type="string")
 * @DiscriminatorMap({"article_vote" = "ArticleVote", "comment_vote" = "CommentVote"})
 */
class Vote
{
    private $id;
    private $weight;
}

class ArticleVote extends Vote
{
    /** @ManyToOne(...) */
    private $article;
}

class CommentVote extends Vote
{
    /** @ManyToOne(...) */
    private $comment;
}
Roy
  • 43,878
  • 2
  • 26
  • 26
rojoca
  • 11,040
  • 4
  • 45
  • 46
  • Hi, thank you for your example, I end up to a similar thing, but there is something I don't understand, in CommentVote you added a $vote property, shouldn't it be $comment as in ArticleVote? – JohnT Apr 29 '11 at 08:46
  • 5
    Vote must be an abstract class or part of a discriminator map, to be properly mapped in the inheritance hierarchy. – hserge Dec 14 '16 at 22:41
3

Just incase someone else needs it, here is an detailed example in using Table Inheritance with Doctrine. I found it more informative than the Doctrine documentation:

http://blog.liip.ch/archive/2012/03/27/table-inheritance-with-doctrine.html

David Lin
  • 13,168
  • 5
  • 46
  • 46