Search code examples
phpmysqlsymfonydoctrine-ormmany-to-many

Doctrine query builder doesn't give all the results : many-to-many searching id in (x,y)


I'm facing some trouble getting my results with doctrine query builder, in a Symfony 2.8 app :

I've got here 3 entities :

  • Song
  • Artist
  • Category

All songs have at least 1 artist and 1 category

Song has manytomany relation with Artist, and manytomany with Category aswell

I would like to get the Songs entities having the same artists OR categories as one song given to this function :

public function findRelatedSongs($song)
{
    $em = $this->getEntityManager();

    $artistsIds = $this->getArtistsIds($song);
    //returns a string like '1,2,3'
    $categoriesIds = $this->getCategoriesIds($song);
    //returns a string like '1,2,3'

    $q = $em->getRepository("BeatAdvisorBundle\Entity\Song")
            ->createQueryBuilder('s')
            ->join('s.artists', 'a')
            ->join('s.categories', 'c')
            ->where('a.id in (:artistsIds)')
            ->orWhere('c.id in (:categoriesIds)')
            ->andWhere('s.id <> :songId')
            ->setParameter('artistsIds', $artistsIds)
            ->setParameter('categoriesIds', $categoriesIds)
            ->setParameter('songId', $song->getId())
            ->getQuery();

    $sql = $q->getSql();
    // here I can read the sql query generated

    $result = $q->setMaxResults(16)
                ->getResult();

    return $result;
}

It gives me back the related songs on same artists, but not on categories.

Is there a problem with the way I wrote this ?

If I copy and paste the sql query, setting the ids as parameters like something_id in (1,2) it works good...

EDIT

Now I know that song-A having only artist-x will match some songs having only artist-x ; same for categories. might be a problem of type (string VS int) causing problems with in(x,y) instead of in (x) ?...


Solution

  • OK, my error was to set my parameters as string (imploded arrays of ids).

    I had to give the array of integers itself...