首页 > 解决方案 > 如何选择与当前用户在所有相同事件中注册的所有用户

问题描述

我正在使用 Symfony 4。我有 3 个实体,UserEventEventRegistration

class User {
 /**
 * @ORM\OneToMany(targetEntity="App\Entity\EventRegistration", mappedBy="user", cascade={"persist","remove"})
 */
public $eventsRegistrations;

}

class Event{
/**
 * @ORM\OneToMany(targetEntity="App\Entity\EventRegistration ", mappedBy="event")
 * @ORM\JoinColumn(nullable=false)
 */
private $registrations;
}

class EventRegistration {
/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Event", inversedBy="registrations")
 * @ORM\JoinColumn(nullable=false)
 */
private $event;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="eventsRegistrations")
 * @ORM\JoinColumn(nullable=false)
 */
private $user;
}

我想知道如何使用一个查询而不是像我做的两个查询来选择与当前用户在所有相同事件中注册的所有用户。

现在我创建了两个查询:

事件注册库

// select all events ids in where the current user has been registered
public function myEventsIds($user)
{
    $arrayEventssIds = array();
    $qb = $this->createQueryBuilder('e')
        ->where('e.user = :user')
        ->setParameter('user', $user)
        ->getQuery()
        ->getResult();
    foreach ($qb as $registration) {
        array_push($arrayEventssIds , $registration->getEvent()->getId());
    }

    return $registration;
}

然后在UserRepository中,选择所有在当前用户的 arrayEventsIds 中具有注册事件 ID 的用户:

public function usersRegistredInTheSameEvents($user, $arrayEventsIds)
{
  //arrayEventsIds contains the events ids selected in the query above

    $qb = $this->createQueryBuilder('u')
        ->innerJoin('u.eventsRegistrations', 'er')
        ->where('er.event IN (:arrayEventsIds)')
        ->andWhere('er.user != :user')
        ->setParameter('arrayEventsIds', $arrayEventsIds)
        ->setParameter('user', $user)
        ->addGroupBy('u.id');

    return $qb->getQuery()->getResult();
}}
 

如何将这两个查询组合在一起?

标签: postgresqldoctrinequery-builder

解决方案


这是您需要的查询的 DQL 版本(用于用户存储库);

$query = $this->_em->createQuery(
        "select u from App:EventRegistration er 
         left join App:User u with er.user = u.id
         where er.user != :user_id and 
         er.event in (select identity(er2.event) from App:EventRegistration er2 
         where er2.user = :user_id)")
->setParameter('user_id', $user->getId());

$users = $query->getResult();

希望有帮助。


推荐阅读