开发者

Doctrine: Select elements that are related to one or more items in many-to-many relation

开发者 https://www.devze.com 2022-12-23 00:58 出处:网络
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?

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消