1
votes

i have relationships (ManyToMany) in symfony2:

Item <-> Category

Database:

Item: ID NAME

Category ID NAME SLUG

Item Category: id item_id category_id

I'm trying to find all the items that are connected with the categories by x slugs.

code does not work:

 $qb = $this->createQueryBuilder('i')
        ->select('i, c ')
        ->leftJoin('i.categories', 'c')

        ->setParameter('firstSlug', 'first')
        ->andWhere('c.slug = :firstSlug')

        ->setParameter('secondSlug', 'second')
        ->andWhere('c.slug = :secondSlug')

Any ideas how to do it?

3
I think setParameter needs to come after the andWhere clauses - Adam Elsodaney
this code: $qb = $this->createQueryBuilder('i') ->select('i, c ') ->leftJoin('i.categories', 'c') ->setParameter('firstSlug', 'first') ->andWhere('c.slug = :firstSlug') retrieve item id : 1 - Michał Soczyński
this code: ->setParameter('secondSlug', 'second') ->andWhere('c.slug = :secondSlug') retrive item id : 1 but I need to pull out items that are here and here (by category slug) - Michał Soczyński
if i use: $qb = $this->createQueryBuilder('i') ->select('i, c ') ->leftJoin('i.categories', 'c') ->setParameter('firstSlug', 'first') ->andWhere('c.slug = :firstSlug') ->setParameter('secondSlug', 'second') ->andWhere('c.slug = :secondSlug') query returns nothing... - Michał Soczyński

3 Answers

0
votes

You've got a double and, and none of your categories have two slugs, so no categories match both c.slug=first and c.slug=second. Try:

$qb = $this->createQueryBuilder('i')
    ->select('i, c ')
    ->leftJoin('i.categories', 'c')

    ->setParameter('firstSlug', 'first')
    ->andWhere('c.slug = :firstSlug')

    ->setParameter('secondSlug', 'second')
    ->orWhere('c.slug = :secondSlug')                <<< change in this line
0
votes
$qb = $this->createQueryBuilder('i');
$qb
    ->select('i')
    ->join('i.categories', 'c')
    ->where($qb->expr()->in('c.slug', ':slugs'))
    ->setParameter('slugs', ['first_slug', 'second_slug', 'third_slug'])
    ->distinct(i.id) // to prevent having same item more than once
;
0
votes

Based on comments, I think you want to use join conditions:

$qb = $this->createQueryBuilder('i');
$qb->select('i, c ')
   ->join('i.categories', 'c', 'ON', 'c.slug = :firstSlug')
   ->join('i.categories', 'c', 'ON', 'c.slug = :secondSlug')
   ->setParameter('firstSlug', 'first')
   ->andWhere('c.slug = :secondSlug')
;

You cannot use left joins, you'll match items that don't have your slugs.