简体   繁体   English

Symfony API创建与现有实体相关的实体

[英]Symfony API create entity with relation to existing entities

I have a Symfony API with two entities : Apartment and User. 我有一个带有两个实体的Symfony API:Apartment和User。 The apartment entity has a field named owner who is a User object. 公寓实体具有一个名为owner的字段,该字段是User对象。

private $owner;

I want to create an Appartment linked to the owner with id 8. I send this JSON : 我想创建一个与所有者链接的ID为8的公寓。我发送此JSON:

{
"title": "Appartement n°144",
"description": "Description de l'appartement 144",
"rooms": 2,
"area": 11.2,
"price": 101.2,
"visible": true,
"location": {
    "latitude": 0,
    "longitude": 0,
    "altitude": 0
},
"owner": 8

} }

I have also tried to change "owner": 8 to "8" or to "owner": {id: "8"}, but I have always this error : 我也尝试将“ owner”:8更改为“ 8”或“ owner”:{id:“ 8”},但是我总是遇到以下错误:

{
"error": {
    "code": 400,
    "message": "Bad Request",
    "exception": [
        {
            "message": "Invalid data \"8\"(integer), expected \"HGB\\CoreBundle\\Entity\\User\".",
            "class": "Symfony\\Component\\HttpKernel\\Exception\\BadRequestHttpException",

If someone has the tips. 如果有人有提示。

Here is my controller : 这是我的控制器:

public function addOneAppartment(Appartment $appartment)
{
    $manager = $this->getDoctrine()->getManager();
    $manager->persist($appartment);
    $manager->flush();

    return $appartment;
}

{id: "8"} should work with JMS, make sure you are using the correct groups. {id: "8"}应该与JMS一起使用,确保使用正确的组。

And make sure to use doctrine object constructor : 并确保使用主义对象构造函数

services:
    jms_serializer.object_constructor:
        alias: jms_serializer.doctrine_object_constructor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM