Reputation: 313
I am building a blog with symfony2 and I am wondering which doctrine relation mapping should be used for the comments. The thing is that I would like to use the comments in different parts, like commenting on pictures (which are not posts) or commenting on comments. So I need my comment entity to be independent of the post.
I wanted to try the OneToMany unidirectionnal but it forces a unique key on the post which is not great.
Thanks for your help
Upvotes: 1
Views: 220
Reputation: 830
The simplest way would be to create a OneToMany
relationship for each linked entity. It's quite ugly and maybe is not effective when searching entities, but it works.
The mapping would be similar to this:
class Comment
{
/**
* @ORM\ManyToOne(targetEntity="Post")
* @ORM\JoinColumn(nullable=true)
**/
protected $post;
/**
* @ORM\ManyToOne(targetEntity="Picture")
* @ORM\JoinColumn(nullable=true)
**/
protected $picture;
/**
* @ORM\ManyToOne(targetEntity="Comment")
* @ORM\JoinColumn(nullable=true)
**/
protected $comment;
}
You'll have to handle security by yourself to make sure the comment has at least ONE linked element, and searching might be harder, but it's a basic way to do it.
The most effective way to do it (but maybe the most complex) would be to create a "discriminant" property and a "element-to-be-commented" property, coupled with a Custom Doctrine hydrator to retrieve all objects at once, but each one being the correct entity.
The "element-to-be-commented" property would then be either a Comment, Picture or Post, and the discriminant would be here to tell which class is linked.
In SQL terms, it means no foreign key between tables, and that the element_id is dependent of the discriminant.
Upvotes: 2
Reputation: 4265
You may want to take a look at Single Table Inheritance. Disclaimer: I don't have direct experience with it, but it's been suggested often as an answer to similar questions.
Upvotes: 0