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.

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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路