postgresql - 如何选择与当前用户在所有相同事件中注册的所有用户
问题描述
我正在使用 Symfony 4。我有 3 个实体,User,Event,EventRegistration。
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();
}}
如何将这两个查询组合在一起?
解决方案
这是您需要的查询的 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();
希望有帮助。
推荐阅读
- flutter - 在 Flutter 中,获取 URL 但无法在 VideoPlayer 上显示视频并出现错误
- plantuml - PlantUML:如何使动作指向动作和项目
- ruby-on-rails - Rails Pg_Search 在没有更改代码的情况下停止工作
- pca - 尝试使用 R 中的 ggbiplot 删除 PCA 中的网格线和背景
- mysql - bash: X: 参数列表太长
- sql-server - SQL 到 SAS ODBC 连接 - NVARCHAR(max) 截断但出现错误:选项 dbtype 不是有效的输出数据集选项
- networking - 通过 Cisco 路由器使用 SSH 连接到 Cisco 交换机
- python-3.x - 'airflow.providers.google.cloud.hooks.gcs' 不是一个包
- java - 如何从 Tab 活动访问我的片段上的列表?
- c# - 仅在 IIS 服务器上的 ConfigureServices 中缺少 ASP.NET Core AddAuthorization 方法