maaudet
maaudet

Reputation: 2358

Doctrine 2, ManyToMany search

I have 2 Doctrine tables that are linked with a ManyToMany relationship.

Table: entries

TabLe: tags

I would like to be able to find the entries that have multiple or one tag(s) matching every tags that I input.

Ex: En entry "foo" have the tag "1" and "2". If I try to find every entries by the tag "1", I find this entry, if I do another search for both "1" and "2" I find it again, but if I add a search for the tag "3", then the value is not matched.

So far I have found some easy methods to implement such thing with an OR, but it doesn't give me the results I want and I don't really know how I could make that kind of search with Doctrine 2.

Normaly I would use the relation table to do that, but I don't know if it's possible under Doctrine.

Upvotes: 1

Views: 181

Answers (1)

Zeljko
Zeljko

Reputation: 5158

Not really sure if I understood, but try if this works:

//class EntryRepository

public function yourFunction($tags)
{
    return $this->createQueryBuilder("o")
       ->innerJoin("o.Tags", "t", "WITH", "t.name IN :tags")
           ->setParameter("tags", $tags)
       ...
}

This will return entries that have at least one of the tags in $tags array. If that is what you want, you might also play with

->addSelect( "COUNT(t.id) as HIDDEN relevance")->groupBy("o.id")
->orderBy("relevance")   

That would return results in order of how many tags are matched, but I didn't test it.

Upvotes: 1

Related Questions