[英]Persisting several entities in 1 post (REST API) in Symfony 4 with FosrestBundle
我想使用fosrestbundle在1個帖子中發布多個實體。 目前,持久化1個實體效果很好,但是我不確定如何對幾個實體進行操作。
我嘗試了,現在是創建一個包含只有1屬性,是myEntity所集合的MyEntityCollection類 :
class MyEntityCollection
{
/*
* @var Collection
*/
protected $myEntities;
/**
* @return mixed
*/
public function getMyEntities()
{
return $this->myEntities;
}
/**
* @param mixed $myEntities
*/
public function setMyEntities($myEntities): void
{
$this->myEntities= $myEntities;
}
/**
* @param MyEntity $myEntity
* @return MyEntityCollection
*/
public function addMyEntity(MyEntity $myEntity): MyEntityCollection
{
$this->myEntities->add($myEntity);
return $this;
}
}
我還創建了一個MyEntityCollectionType formType :
class MyEntityCollectionType extends AbstractType
{
/**
* This function sets the fields of the form
* @param FormEvent $event the PRE_SET_DATA event
*/
public function setFields(FormEvent $event): void
{
$form = $event->getForm();
$form
->add('myEntities', EntityType::class, array(
'required' => true,
'multiple' => true,
'class' => MyEntity::class
));
//->add('myEntities', CollectionType::class, array(
// 'required' => true,
// 'data_class' => MyEntity::class
//));
}
我的控制器動作如下所示:
protected function processForm($entity, String $entityTypeClass, $request)
{
if (empty($entity)) {
throw new NotFoundHttpException('Entity not found');
}
$form = $this->createForm(
$entityTypeClass,
$entity
);
$form->submit($request->request->all(), false);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $entity;
}
return $form;
}
/**
* @Rest\View(statusCode=Response::HTTP_CREATED)
* @Rest\Post("/myEntity-collection")
* @param Request $request
* @return object
*/
public function postMyEntityCollectionAction(Request $request): object
{
$myEntityCollection = new MyEntityCollection();
return $this->processForm($myEntityCollection, MyEntityCollectionType::class, $request);
}
當我嘗試將數據發布到路由時,出現以下錯誤: 類“ App \\ Enablon \\ Checklist \\ Desktop \\ Domain \\ MyEntityCollection”不是有效的實體或映射的超類。
需要明確的是,我不想持久化MyEntityCollection實體,而只是幾個MyEntity,但是在我看來,如果需要將其暴露在發布路線中,那么這是一種創建實體類的干凈方法。
也許我只是沒有采取正確的方法,所以我真的很樂意接受任何建議,但是在我看來,這似乎是實現我想要做的事情的一種干凈的方法。
我不確定這樣做是否正確,但這是一個可行的案例:
我刪除了MyEntityCollection實體及其表單類型。 相反,我在控制器中執行此操作:
/**
* @Rest\View(statusCode=Response::HTTP_CREATED)
* @Rest\Post("/myentity-collection")
* @param Request $request
* @return object
*/
public function postMyEntityCollectionAction(Request $request)
{
$validation = array();
foreach ($request->request->all() as $myEntityRequest) {
$validation[] = $this->processForm(new MyEntity(), MyEntityType::class, $myEntityRequest);
}
return $validation;
}
我只是在MyEntity上發布一個數組作為路線的參數。
這樣,驗證錯誤就更容易理解,因為它們都在控制器返回的$ validation數組中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.