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条回答 默认 最新

相关推荐 更多相似问题