Symfony 4教义持久性与存在于数据库中的关联的对象

时间:2018-12-07 20:23:54

标签: doctrine-orm associations entity-relationship symfony4

我通过与jms序列化程序的关联来使整个对象失效。

$obj = $serializer->deserialize($serializer->serialize($data, 'json'), 'array<App\Entity\Company>', 'json');

生成的对象外观

Company {#521
  -addresses: ArrayCollection {#557
    -elements: array:2 [
      0 => Address {#544
        -id: null
        -company: Company {#521}
        -type: AddressType {#552
          -id: null
          -name: "Main Address"
        }
      }
      1 => Address {#554
        -id: null
        -company: Company {#521}
        -type: AddressType {#556
          -id: null
          -name: "Correspond Address"
        }
      }
    ]
  }
 }

公司

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Address", mappedBy="company", orphanRemoval=true, cascade={"persist","remove"})
 * @JMS\Accessor(setter="setAddresses")
 */
 private $addresses;

地址

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Company", inversedBy="addresses")
 * @ORM\JoinColumn(nullable=false)
 *
 */
private $company;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\AddressType", cascade={"persist","remove"})
 * @ORM\JoinColumn(nullable=false)
 */
private $type;

AddressType

/**
 * @ORM\Column(type="string", length=255, unique=true)
 */
private $name;

现在,我尝试保留该对象并将其刷新到数据库,但是当AddresType-> name存在时,我从db获取有关现有值的错误。这是db的正常行为,因为键名是唯一的,并且学说会尝试INSERT

如果数据库中存在对象以使用它而不是尝试插入,该如何添加关系?

0 个答案:

没有答案