Doctrine: Select elements that are related to one or more items in many-to-many relation
I have a category system that is related many-to-many with posts. How can I select a list of those categories that are related to one or more posts?
$q = Doctrine_Query::create()
->from('Category c开发者_如何转开发')
->where('<DONT KNOW WHAT TO WRITE>')
->select('c.name');
Create equivalent of this in DQL:
SELECT c.*
FROM category c
INNER JOIN category_post_rel cpr ON c.id = cpr.category_id;
EDIT:
DQL equivalent:
Doctrine_Query::create()
->select('c.name')
->from('Category c')
->innerJoin('c.Posts');
Unfortunately that will also join Post
table. You should consider using additional field post_count
in Category
model. Its value should be equal to category's relation count. This is very common solution (cause it's really fast) for this and many other problems).
->where('post_id = \'CURRENT_POST\'')
I don't know the syntax for Doctrine Query, so this is just a guess. Replace CURRENT_POST with the post you want to check.
精彩评论