【问题标题】:Doctrine Order OneToMany collectionDoctrine Order OneToMany 集合
【发布时间】:2019-03-01 15:28:35
【问题描述】:

您好,我正在尝试按多个字段订购学说集合

试过这样的

  /**
     * @var Collection
     * @ORM\OrderBy({"date" = "ASC","TimeBegin" = "ASC"})
     * @ORM\OneToMany(targetEntity="Schedule", mappedBy="event")
     */
    protected $schedules;

此代码无效

日期字段的格式为“1927-12-01” timeBegin "00:13:01"

这是我的查询

 public function getAppointmentDetails(int $eventId): ?Event
    {

        $eventAlias = 'event';
        /** @var EventQueryBuilder $queryBuilder */
        $queryBuilder = $this->createQueryBuilder($eventAlias);

        $queryBuilder->select($eventAlias)
            ->whereEventId($eventId)
            ->withRoom()
            ->withService()
            ->withSchedulesAndInstructorsOrderedByDateAndTime();


        $appointmentDetails = $queryBuilder->getQuery()->getOneOrNullResult();

        return $appointmentDetails;
    }

和我的方法与SchedulesAndInstructorsOrderedByDateAndTime

 /**
     * With Schedules And Instructors Ordered by Date and Time
     * @return EventQueryBuilder
     */
    public function withSchedulesAndInstructorsOrderedByDateAndTime() : EventQueryBuilder
    {
        $this->join($this->getRootAliases()[0] . '.schedules', 'sc');
        $this->join('sc' . '.instructors', 'in');

        return $this;
    }

问题是,如果我添加 orderBy,我的讲师收藏将是空的

【问题讨论】:

  • 不确定是否可以使用 Annotations,但您可以使用 QueryBuiler 轻松实现,请参阅 stackoverflow.com/questions/11575325/…
  • OrderBy 支持多个字段,并且您的语法在该帐户上看起来是正确的。那么究竟是什么不适合您的代码?您能否提供一组结果实体列表的示例(以及相关的日期和时间开始值)?
  • 是的,我肯定会发布我的查询生成器
  • 我怀疑这行不通,因为我在加入时间表后立即加入了讲师实体
  • 好的,所以与原始信息相比,您在那里做了更多的事情:) 所以只是为了仔细检查,当您从关联映射中删除 orderBy 时,相同的存储库函数会返回一些东西?也许您可以在这两种情况下打印出准备好的 sql 语句,将它们修改为 sql 查询并针对您的数据库运行这些语句,看看这两种情况之间到底有什么不同?

标签: symfony doctrine


【解决方案1】:

如文档所述:

为了降低对数据库的影响,这些隐式 ORDER BY 项仅在 DQL 查询中加入 fetch 时才会添加到 DQL 查询中。

因此,您需要通过将 Schedule 添加到您的选择来进行 fetch 连接:

    /**
     * With Schedules And Instructors Ordered by Date and Time
     * @return EventQueryBuilder
     */
    public function withSchedulesAndInstructorsOrderedByDateAndTime() : EventQueryBuilder
    {
        $this->addSelect('sc');
        $this->join($this->getRootAliases()[0] . '.schedules', 'sc');
        $this->join('sc' . '.instructors', 'in');

        return $this;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多