How to add related object to an embedded collection and set the other side? #5360
-
Am I missing something? I have a See the request: {
// ...
"objects": [
{
// ...
},
{
// ...
}
]
} See the resources: #[ORM\Entity]
#[ApiResource(
operations: [new GetCollection(), new Get(), new Post(), new Patch(), new Delete()],
normalizationContext: ['groups' => ['container:read']],
denormalizationContext: ['groups' => ['container:write']],
)]
class ContainerClass
{
// ...
/**
* @var Collection<MyObject>
*/
#[ORM\OneToMany(targetEntity: MyObject::class, mappedBy: 'containerClass', cascade: ['persist'], orphanRemoval: true)]
#[Groups(['container:read', 'container:write'])]
private Collection $objects;
public function __construct()
{
$this->objects = new ArrayCollection();
}
/**
* @return Collection<MyObject>
*/
public function getObjects(): Collection
{
return $this->objects;
}
public function addObject(MyObject $object): static
{
$objects = $this->getObjects();
if (! $objects->contains($object)) {
$objects[] = $object;
if ($this !== $object->getContainerClass()) {
$object->setContainerClass($this);
}
}
return $this;
}
public function removeObject(MyObject $objects): static
{
$objects = $this->getObjects();
if ($objects->contains($object)) {
$objects->removeElement($object);
if ($this === $object->getContainerClass()) {
$object->setContainerClass(null);
}
}
return $this;
}
} #[ORM\Entity]
#[ApiResource(
operations: [new GetCollection(), new Get(), new Post(), new Patch(), new Put(), new Delete()],
normalizationContext: ['groups' => ['object:read']],
denormalizationContext: ['groups' => ['object:write']],
)]
class MyObject
{
#[ORM\ManyToOne(targetEntity: ContainerClass::class, inversedBy: 'objects', cascade: ['persist'])]
#[ORM\JoinColumn(nullable: false)]
#[NotBlank]
#[Groups(['object:read'])]
private ?ContainerClass $containerClass = null;
public function getContainerClass(): ?ContainerClass
{
return $this->containerClass;
}
public function setContainerClass(?ContainerClass $containerClass): static
{
$this->containerClass = $containerClass;
$this->containerClass?->addObject($this);
return $this;
}
} As you can see, if the collection is updated using |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
It was a naming problem with the |
Beta Was this translation helpful? Give feedback.
It was a naming problem with the
add
&remove
methods. Closing it now.