我在symfony2中有关系(ManyToMany):
项目< - >分类
数据库:
档案: ID NAME
类别 ID NAME SLUG
项目类别: id item_id category_id
我正在尝试通过x slugs找到与类别相关的所有项目。
代码不起作用:
$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')
任何想法怎么做?
答案 0 :(得分:0)
你有一个双倍的,并且没有一个类别有两个slu,所以没有类别匹配c.slug = first和c.slug = second。尝试:
$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
答案 1 :(得分:0)
$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
;
答案 2 :(得分:0)
根据评论,我认为你想使用连接条件:
$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')
;
你不能使用左连接,你将匹配没有你的slu。的项目。