dsijovl015728613 2015-02-28 23:39
浏览 59
已采纳

Symfony2和Doctrine:使用查询构建器的多对多关系

I have 2 entities: User and Archive. The user entity has, among others, two properties:

/**
 * @ORM\OneToMany(targetEntity="My\ApplicationBundle\Entity\Archive", mappedBy="user")
 **/
protected $archives;

/**
 * @ORM\ManyToMany(targetEntity="My\ApplicationBundle\Entity\Archive", inversedBy="users")
 * @ORM\JoinTable(name="collection")
 **/
private $collection;

and the Archive entity:

/**
 * @ORM\ManyToOne(targetEntity="My\UserBundle\Entity\User", inversedBy="archives")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
 **/
protected $user;

/**
 * @ORM\ManyToMany(targetEntity="My\UserBundle\Entity\User", mappedBy="collection")
 **/
private $users;

the reason of this little mess is pretty simple: in User, $archives represent all the archives submitted by a user, $collection represent all the archives used by a user (even submitted by other users). In Archive entity, $user represent the user that submitted this archive, $users represent all the users using this archive.

So, to get the archives of one user I simply use to do:

$this->getUser()->getArchives();

and to get the collection:

$this->getUser()->getCollection();

the problem now is I have to paginate the results, so I need to use query builder. what I am doing is:

$repository = $this->getDoctrine()
        ->getRepository('MyApplicationBundle:Archive');

    $query = $repository->createQueryBuilder('a')
        ->innerJoin('a.user', 'u', 'WITH', 'u = :user')
        ->where('a.active = :active')
        ->setParameters(array(
            'user' => $this->getUser(),
            'active' => 1
        ))
        ->setFirstResult($start)
        ->setMaxResults($length)
        ->getQuery()
        ->getResult();

but here the problem is I am going directly to Archive without using the collection table (there is not an entity for that). Can anyone please explain me hot to consider the collection table to filter my results?

Many thanks Manuel


SOLVED

thanks to LPodolski, this is how I changed the DQB

$query = $repository->createQueryBuilder('a')
        //->innerJoin('a.user', 'u', 'WITH', 'u = :user')
        ->innerJoin('a.users', 'cu', 'WITH', 'cu = :user')
        ->where('a.active = :active')
        ->setParameters(array(
            'user' => $this->getUser(),
            'active' => 1
        ))
        ->setFirstResult($start)
        ->setMaxResults($length)
        ->getQuery()
;
  • 写回答

1条回答 默认 最新

  • douxi2011 2015-03-01 08:10
    关注
    >innerJoin('a.users', 'cu', 'WITH', 'cu = :collectionUser')
    

    or leftJoin should do the trick

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料