我有三个表/实体的结构:User
(表users
;列id
和name
),Room
(表roome
;列id
和number
)和RoomUser
(user_room
;列id
,user_id
,room_id
)。
现在我想检索具有给定id
的User
的所有Room
。如何在不加入Room
的情况下做到这一点?
$userId = 123;
// ...
$queryBuilder = $this->entityManager->createQueryBuilder();
$query = $queryBuilder->select('r')
->from(Room::class, 'r')
->join('r.RoomUsers', 'ru')
->where('ru.room_id = :userId') // room_id? ru.Room.id?
->setParameter('userId', $userId)
->getQuery();
$rooms = $query->getResult(Query::HYDRATE_OBJECT);
所以在SQL中它会像
SELECT *
FROM rooms
JOIN room_users ON room_users.room_id = rooms.id
WHERE user_id = 123;
如何使用QueryBuilder
实现这个简单的请求?
您可以使用
MEMBER OF
(文档)来实现:
$query = $queryBuilder->select('r')
->from(Room::class, 'r')
->where(':user_id MEMBER OF r.users')
->setParameter('user_id', $userId)