How can i create a relationship between entities with Symfony 2 and Doctrine? I’m only able to create standalone entities. Maybe someone can help me figure this out using the entity generator? I want to:
- Create two entities: Post and Category. A Post is part of a Category.
- Create a Tag entity: A Post can have many Tags.
A practical example is covered in Symfony2 docs here:
http://symfony.com/doc/current/book/doctrine.html#entity-relationships-associations
To elaborate, taking the first example, you need to create a
OneToManyrelationship between yourCategoryobject and yourPostobject:Category.php:
Post.php
This should get you started. I’ve just written this so there might be errors :s
I’m making properties
$postsand$categorypublic here for brevity;however you’d probably be advised to make these private and add setters/getters to your classes.Also note that
$postsis an array-like DoctrineArrayObjectclass especially for arrgregating entities, with methods like$category->posts->add($post)etc.For more detail look into association mapping in the Doctrine documentation. You’ll probably need to set up a
ManyToManyrelationship betweenPostsandTags.Hope this helps 🙂