【问题标题】:JMS Serializer not working on custom repository method with FOSRestJMS 序列化程序无法使用 FOSRest 处理自定义存储库方法
【发布时间】:2017-02-13 17:25:53
【问题描述】:

我在设置 JMS Serializer 和 FOSRestBundle 以序列化此自定义存储库方法时遇到问题。

如果我使用$schedules = $em->getRepository('RadioBundle:Schedule')->findAll();,它可以正常工作,但是当我尝试我的自定义方法时,不会排除任何字段。

谁能帮我找出问题所在?

控制器:

use RadioBundle\Entity\Schedule;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\Annotations\View;


class ScheduleController extends BaseController
{
    /**
     * @param $date
     * @return \Symfony\Component\HttpFoundation\Response
     * @View(serializerGroups={"schedule"})
     */
    public function getSchedulesScheduleAction($date)
    {
        $em = $this->getDoctrine()->getManager();
        list($startDate, $endDate) = $this->get('radio.utils.date_and_time')->findWeekRange($date);
        $schedules = $em->getRepository('RadioBundle:Schedule')->findByRange($startDate, $endDate);

        $view = $this->view(
            [
                'schedules' => $schedules,
            ],
            200
        );

        return $this->handleView($view);
    }
}

存储方法:

class ScheduleRepository extends EntityRepository
{
    /**
     * @param \DateTime $startDate
     * @param \DateTime $endDate
     * @return array
     */
    public function findByRange(\DateTime $startDate, \DateTime $endDate)
    {
        $em = $this->getEntityManager();
        $qb = $em->createQueryBuilder();
        $qb->select('s')
            ->from('RadioBundle:Schedule', 's')
            ->leftJoin('s.radioShow', 'rs')
            ->add(
                'where',
                $qb->expr()->between(
                    's.startTime',
                    ':from',
                    ':to'
                )
            )
            ->orderBy('s.startTime', 'asc')
            ->andWhere('rs.isActive = true')
            ->setParameters(['from' => $startDate, 'to' => $endDate]);

        return $qb->getQuery()->getArrayResult();
    }
}

【问题讨论】:

  • 序列化工作需要真正的实体而不是数组,请查看@martin 答案,这是您问题的解决方案。

标签: doctrine-orm symfony fosrestbundle jmsserializerbundle


【解决方案1】:

如果您使用 getArrayResult() 从您的方法返回结果,它会生成嵌套数组而不是实体对象。

JMSSerializer 需要知道您正在序列化哪些类以加载正确的元数据。所以你应该改用getResult()

【讨论】:

  • 我不知道锻炼需要多长时间,非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-01-24
  • 2013-09-09
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
相关资源
最近更新 更多