Symfony 6.3 /使用MapRequestPayload发布请求

7eumitmz  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(91)

我想使用MapRequestPayload属性从POST请求数据创建一个实体。
然后验证它,然后保存它。
到目前为止,这工作得很好,但是如何处理来自select的数据呢?

{
    "name": "test",
    "firstname": "test",
    "company_id": 486
}

compay_id是一个在前端的选择。
在赋值时,这当然会被忽略,这是可以的,因为它不应该被创建,但是关系应该被保存。
我现在的方法如下,但它不起作用,因为MapEntity属性引用了RequestQuery。

public function add(
        #[MapRequestPayload] Person $person,
        #[MapEntity(id: 'company_id')] Company $company
    ): JsonResponse
    {
        $person->setCompany($company);
    }

你知道怎么做吗?

lymnna71

lymnna711#

首先通过JavaScript可以有两种解决方案。

fetch('api/users?company_id='.$companyId, {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Accept": "application/json",
  },
  body: JSON.stringify({
    name: "test",
    firstName: "test"
  })

})

通过Symfony的ValueResolverInterface
https://symfony.com/doc/current/controller/value_resolver.html#adding-a-custom-value-resolver

相关问题