给出两个表:
通知
id (int PK)
title (varchar(255))
date (datetime)
notification_seen
id (int PK)
notification_id (int FK)
user_id (int FK)
用户
id (int PK)
映射为简单的Doctrine实体,其中通知的关系定义如下:
@ORM\OneToMany(targetEntity="NotificationSeen", mappedBy="notification")
private $seenBy;
和 NotificationSeen :
@ORM\ManyToOne(targetEntity="Notification", inversedBy="seenBy")
@ORM\JoinColumn(name="notification_id")
private $notification;
@ORM\ManyToOne(targetEntity="User", inversedBy="seen")
@ORM\JoinColumn(name="user_id")
private $user;
和用户实体:
@ORM\OneToMany(targetEntity="NotificationSeen", mappedBy="users")
private $seen;
我想选择所有通知对象不通过 seenBy 关系连接。
如何使用QueryBuilder在NotificationRepository中选择此类实体?任何帮助将不胜感激。
更新
NotificationRepository :
中的当前方法实现public function getUnreadNotification(User $user): array
{
return $this->createQueryBuilder('u')
->orderBy('u.date', 'desc')
->getQuery()
->getResult();
}
答案 0 :(得分:0)
基本上您只想查询没有相关Notifications
的{{1}}数据库:
NotificationSeen
答案 1 :(得分:0)
以下是我对迈克评论的建议
[...]可以这么说,我需要从通知表中选择指定用户的notification_seen表中不存在的所有实体。
我没试过,但它应该有用。
public function getUnreadNotifications(User $user)
{
// Create query builder
$qb = $this->createQueryBuilder('n');
// someone saw the notification
$nobodySawIt = $qb->expr()->eq('SIZE(n.seenBy)', 0);
// Create expression for 'another guy saw the notification, but not my user'
$someOneElseSawIt = $qb->expr()->andX(
$qb->expr()->neq('SIZE(n.seenBy)', 0), // someone saw the notification
$qb->expr()->neq('u.id', $user->getId()) // but not this user
);
// Create the query
$qb
->leftJoin('n.seenBy', 's') // Join on NotificationSeen
->leftJoin('s.user', 'u') // Join on User
->orWhere($nobodySawIt) // I want unread notifications
->orWhere($someOneElseSawIt); // and notifications that this guys didn't read yet
/*
->addOrderBy(alias.property)
->setFirstResult($offset)
->setMaxResults($limit);
*/
return $qb->getQuery()->getResult();
}
告诉我是否有问题