我有实体Product和Host
产品
-------------------------------------------------
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。
如何以及在何处正确创建主机?
在这种情况下,我需要在控制器中创建产品和主机吗?
答案 0 :(得分:1)
您可以在发送数据时创建z3
:
Site
Api平台应该创建主机,前提是正确定义了实体,并且{
url: http://exmaple2.com/2/3/4,
name: super_product,
host: {"host": "example.com"}
}
属性是可写的。
或者,您可以使用Doctrine event listener,它会在创建host
时自动触发。
创建一个订户类:
Product
您可以在Doctrine documentation上找到不同的事件。
使用// 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.event_subscriber