【问题标题】:Symfony API Platform. How properly insert complex data?Symfony API 平台。如何正确插入复杂数据?
【发布时间】:2018-12-09 06:17:00
【问题描述】:

我有实体产品和主机

产品

-------------------------------------------------
id   host_id           url               name
-------------------------------------------------
1      1    http://example.com/1/2/3   product_1

主持人

----------
id   host   
----------
1    example.com

当我添加一个产品时,如果我还没有一个主机,我需要创建一个主机(来自 url)并在 host_id 中替换一个 id

例如我发送产品数据

{
    url: http://exmaple2.com/2/3/4
    name: super_product
}

那些。在创建产品之前,我需要创建一个主机(example2.com)。然后将 id 插入到 Product 中的 host_id 中。

我应该如何以及在哪里正确创建主机?

那么,我需要在控制器中创建Product和Host吗?

【问题讨论】:

    标签: php api symfony api-platform.com


    【解决方案1】:

    您可以在发送数据时创建Site

    {
        url: http://exmaple2.com/2/3/4,
        name: super_product,
        host: {"host": "example.com"}
    }
    

    如果实体定义正确且host 属性是可写的,则API 平台应该创建主机。


    或者,您可以为此使用Doctrine event listener,它会在创建Product 时自动触发。

    创建订阅者类:

    // src/EventListener/SearchIndexerSubscriber.php
    namespace App\EventListener;
    
    use Doctrine\Common\EventSubscriber;
    use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
    use App\Entity\Product;
    use Doctrine\ORM\Events;
    
    class ProductListener implements EventSubscriber
    {
        public function getSubscribedEvents()
        {
            return array(
                Events::postPersist,
            );
        }
    
        public function postPersist(LifecycleEventArgs $args)
        {
            $entity = $args->getObject();
    
            if ($entity instanceof Product) {
                // Create site
                $site = new Site();
                // Set data you need
                $site->setUrl(…);
                // Create site
                $entity->setSite($site);
    
                $entityManager = $args->getObjectManager();
                $entityManager->persist($product);
                $entityManager->flush();
            }
        }
    }
    

    你可以在Doctrine documentation找到不同的事件。

    使用doctrine.event_subscriber 标记服务:

        App\EventListener\ProductListener:
            tags:
                - { name: doctrine.event_subscriber }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多