views:

202

answers:

2

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');
A: 
    ->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.

Jonah Bron
I HAVE tables. I need to make query that selects only those categories that are connected to one or more posts.
Migol
Then you need something like `SELECT category_id FROM indexes WHERE post_id = 'this_post'`. I've never used the class you are using, but you should be able to easily translate that over.
Jonah Bron
I assumed you didn't have an index table because the query in your original question was looking in the category table.
Jonah Bron
+3  A: 

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).

Crozin
I know equiwalent, but I don't know how to write it in Doctrine.
Migol
I've updated my answer.
Crozin