2014-01-07 74 views
0

之前,我试过搜索功能,但没有找到关于这一个线程。 继承人我的问题。我正在使用具有多对多关系的教义查询生成器。symfony2 doctirne多对多查询

$qb = $this->getDoctrine()->getRepository('SOMEBUNDLE:INSERTION')->createQueryBuilder('insertion'); 
     $qb->select(' 
     insertion.id, 
     insertion.title, 
     insertion.content, 
     insertion.insertionpicture, 
     insertion.timestamp, 
     insertion.isanon, 
     user.firstname as user_firstname, 
     user.lastname as user_lastname, 
     user.picture as user_picture, 
     supertag.name as supertag_name 
     '); 
     $qb->from('SOMEBUNDLE:USER', 'user'); 
     $qb->from('SOMEBUNDLE:SUPERTAG', 'supertag'); 
     $qb->from('SOMEBUNDLE:TAG', 'tag'); 
     $qb->andWhere('insertion.user = user.id'); 
     $qb->andWhere('insertion.supertag = supertag.id'); 
     $qb->andWhere("insertion.tag = :tag"); 
     $qb->setParameters('tag', $tags); 
     return new JsonResponse($qb->getQuery()->getArrayResult()); 

Insertion.php

/** 
    * @var \Doctrine\Common\Collections\Collection 
    */ 
    private $tag; 

在这里 “andwhere(insertion.tag =:标签)” 我的参数是一个数组。我得到了无效的路径表达式异常,因为我不知道如何为一个Doctrine集合设置参数。通过这个

$qb->andWhere("insertion.tag = :tag"); 

:反正

$qb->andWhere(
    $qb->expr()->in('insertion.tag', $tags) 
); 

,您可以通过链接调用查询生成器减少您的代码:

THX

+0

什么是$ tags'参数? 数组? –

+0

是这样的: 阵列(2){ [0] => 串(3) “乐趣” [1] => 串(4)的 “帮助” } – HaemskiTheBoss

+0

在实体或阵列只包含字符串? –

回答

0

尝试更换此

$qb = $this->getDoctrine() 
    ->getRepository('SOMEBUNDLE:INSERTION') 
    ->createQueryBuilder('insertion'); 

$query = $qb 
    # select only some columns from the tables 
    ->select('partial insertion.{id, title, content, '.' 
     insertionpicture, timestamp, isanon}, '. 
     'partial user.{id, firstname, lastname, picture}, '. 
     'partial supertag.{id, name} ' 
    ) 
    # if the Doctrine association is correct, joins are easy 
    ->leftJoin('insertion.user', 'user') 
    ->leftJoin('insertion.supertag', 'supertag') 
    ->leftJoin('insertion.tag', 'tag') 
    ->andWhere(
     $qb->expr()->in('tag.name', $tags) 
    ); 

return new JsonResponse($query->getQuery()->getArrayResult());