Doctrine单表继承查询所有实例

Jas*_*Lin 5 php doctrine single-table-inheritance dql symfony

我正在研究通知系统,所以我有一个通知抽象类和子类(forumPostNotification,privateMessageNotification等).它们使用单​​表继承存储,因此它们都在一个具有区分字段的表中.

我希望立即获得适用于用户的所有通知,而不必单独查询每种类型的通知,但是我不确定如何在DQL/symfony中执行此操作(在SQL中这很容易).

我相信这一点:( 主义2:如何编写一个DQL select语句来搜索一些,但不是单个表继承表中的所有实体)类似于我想要实现的,但我不知道如何查询抽象对象.它也不在Entity目录中,而是在Entity/Notifications/Notification.php中.

我将添加一些代码以便澄清:

Notification.php

/**
 * Notification Class    
 *@ORM\Entity
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", type="string")
 * @ORM\DiscriminatorMap({
 *     "notification"="Notification",
 *     "forumPostNotification"="ForumPostNotification",
 *     ...
 * })
 * @ORM\Table(name="notification")
 */
abstract class Notification
{
  /**
   * @ORM\ManyToOne(targetEntity="Acme\MainBundle\Entity\User", inversedBy="notifications")
   * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
   */
  private $user;
  //...
}
Run Code Online (Sandbox Code Playgroud)

ForumPostNotification.php

/**
 * Forum Post Notification
 * @ORM\Entity
 */
class ForumPostNotification extends Notification
{
  //..
}
Run Code Online (Sandbox Code Playgroud)

PrivateMessageNotification.php

/**
 * Private Message Notification
 * @ORM\Entity
 */
class PrivateMessageNotification extends Notification
{
  //..
}
Run Code Online (Sandbox Code Playgroud)

我希望能够以这样或那样的方式做这样的事情(我明白我不能从Notification中查询,因为它是一个抽象类.我只是这样写它来传达我想要实现的东西):

$notifications = $em->createQuery('
  SELECT n
  FROM AcmeMainBundle:Notification n
  WHERE n.dateDeactivated IS NULL
  ORDER BY n.dateCreated ASC
')->getResult();
Run Code Online (Sandbox Code Playgroud)

小智 2

我们在订单和产品方面也造成了类似的情况。因为一个订单中可以有不同类型的产品,所以我们创建了一个父类 Product 并继承了 ex。特殊产品、销售产品等

我们能够定义订单(在您的情况下为用户)和“产品”(在您的情况下为通知)之间的关系,仅此而已。我们通过 $order->getProducts() 获取订单的所有产品。该方法返回给我们一个精心准备的具有特定类别的产品列表,例如

order->products[SingleProduct, SingleProduct, SingleProduct, SpecialProduct, SalesProduct, SingleProduct]
Run Code Online (Sandbox Code Playgroud)

所以,总而言之。要获取每个用户的所有通知,您只需要做一件事就是定义用户和抽象父类之间的正确关系。

这很简单,但是......当您只收到来自特定类型的通知时,这不太好。您的链接中传递的查询并不漂亮。在我看来,你应该创建一个合适的 queryBuilder - 它非常相似。

最后你不能使用 $user->getNotifications(),但你必须直接从存储库获取通知 -

$em->get('AcmeBundle:User')->getForumPostNotifications()  
Run Code Online (Sandbox Code Playgroud)

亲切的问候, 彼得·帕西奇