dongyuluan7494 2017-11-25 11:12
浏览 37
已采纳

Controller不会在Symfony 2中返回OneToMany关系字段

I need return full response with Document model. I have response but there are absent some fields, which are defined in entity. For example I need to have in response both 'campaign' and 'template' properties - but actually 'campaign' is absent.

Below are my controller and entity.

I have such action in my controller:

/**
 * @REST\View(serializerGroups={"Default", "DocumentDetails"})
 * @REST\Get("/{id}", requirements={"id" = "\d+"})
 * @ParamConverter("document", class="AppBundle:Document");
 */
public function showAction(Request $request, Document $document)
{
    return $document;
}

But the Document entity has relations:

/**
* Document entity
 *
 * @ORM\Entity(repositoryClass="AppBundle\Repository\DocumentRepository")
 * @ORM\Table(name="document")
 * @ORM\HasLifecycleCallbacks()
 *
 * @Serializer\ExclusionPolicy("all")
 */
class Document
{
.......

/**
 * @var campaign
 * @ORM\ManyToOne(targetEntity="Campaign", inversedBy="documents")
 * @ORM\JoinColumn(name="campaign", referencedColumnName="id")
 *
 * @Serializer\Expose()
 */
protected $campaign; // **THIS FIELD IS ABSENT - WHY !???** 

/**
 * @var DocumentTemplate Szablon dokumentu
 *
 * @ORM\ManyToOne(targetEntity="DocumentTemplate")
 * @ORM\JoinColumn(name="template_id", referencedColumnName="id")
 *
 * @Serializer\Expose()
 */
protected $template; // **THIS PROPERTY IS DISPLAYED**

.......

$document->template is present in $document response. But $document->campaign is absent. What is wrong ? Probably it is related somehow to serializerGroups ?? Thanks for any help.

  • 写回答

1条回答 默认 最新

  • doumengjing1500 2017-11-27 12:16
    关注

    Solved ! Thanks everyone for the help. The issue was related to JMSSerializer. There was need to set this serializer in config file services.yml at first:

    app.serializer.listener.document:
        class: AppBundle\EventListener\Serializer\DocumentSerializationListener
        tags:
            - { name: jms_serializer.event_subscriber }
    

    And then create this listener which is creating form child-field campaign and inserting there Campaign object:

    <?php
    
    
    namespace AppBundle\EventListener\Serializer;
    
    
    use AppBundle\Entity\Campaign;
    use AppBundle\Entity\Document;
    use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
    use JMS\Serializer\EventDispatcher\ObjectEvent;
    
    class DocumentSerializationListener implements EventSubscriberInterface
    {
        /**
         * @param ObjectEvent $event
         * @return void
         */
        public function onPostSerialize(ObjectEvent $event)
        {
            $entity = $event->getObject();
    
            if (!($entity instanceof Document)) {
                return ;
            }
    
            $groups = $event->getContext()->attributes->get('groups')->getOrElse([]);
    
            if (in_array('DocumentDetails', $groups)) {
                $visitor = $event->getVisitor();
    
                $campaign = $this->getCampaignClone($entity->getCampaign());
    
                if ($visitor->hasData('campaign')) {
                    $visitor->setData('campaign', $campaign);
                } else {
                    $visitor->addData('campaign', $campaign);
                }
            }
        }
    
        /**
         * @inheritdoc
         */
        public static function getSubscribedEvents()
        {
            return [
                [
                    'event' => 'serializer.post_serialize',
                    'class' => 'AppBundle\Entity\Document',
                    'method' => 'onPostSerialize'
                ]
            ];
        }
    
        private function getCampaignClone(Campaign $documentCampaign)
        {
            $campaign = new \stdClass();
            $campaign->id = $documentCampaign->getId();
            $campaign->title = $documentCampaign->getTitle();
            $campaign->status = $documentCampaign->getStatus();
            $campaign->rows = $documentCampaign->getRows();
            $campaign->createdAt = $documentCampaign->getCreatedAt()->format(DATE_W3C);
            $campaign->updatedAt = $documentCampaign->getUpdated()->format(DATE_W3C);
    
            return $campaign;
        }
    }
    

    This looks weird I know - but this only solution I found to force inserting the Entity into the form request.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页