简体   繁体   中英

Symfony bind many entity types OneToMany to one entity

I've got a couple of entities and one entity "Comment", which has only string content. I want other entities to be "commentable", so every object of their type could have many Comments.

Can I somehow set OneToMany relation of those entities with Comment in a way that wouldn't make a mess in the db? I am interested in a solution that wouldn't require me to create a field for every commentable entity inside of Comment entity, pointing to the specific entity the comment is for. Something that would make Comment entity hold the ID of commented object and its type. Is it possible?

For sure it's possible:

1) Create an entity 'Comment' with the fields: id, class_name (string), class_id (int, when your ids are integers) and comment (string).

2) When creating a new comment you save the class name of the entity where the comment belongs to, the class_id of the the object the comment belongs to and your comment.

3) Create a function in your Entities repository (or create a trait) which is using the eg the QueryBuilder to retrieve all comments by class_id etc.

Step 3 applies as well for all updates/deletes etc. because as there won't be any managed association in Doctrine for you you'll have to handle it on your own.

Have fun.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM