Answer the question
In order to leave comments, you need to log in
How to use Doctrine to persist related entities?
Hello. I have one project written in pure PHP.
I create a Company entity in it using a handler (well, my implementation of CommandBus). Each company has a service that it provides - an array of company_services
. There was a question about connection to all this Symfony. But ok - I connected the commandbass with Messenger, made the value object using Embeddable, the question remained how to add the company's services to the repository.
/**
* @ORM\Entity(repositoryClass=CompanyRepository::class)
* @Table(name="company")
*/
final class Company {
/**
* @Embedded(class = "Id",columnPrefix=false)
*/
private Id $id;
/**
* @Embedded(class = "Inn",columnPrefix=false)
*/
private Inn $inn;
/**
/**
* @ORM\OneToMany(targetEntity="App\Company\Domain\Entity\CompanyServices", mappedBy="company")
* @Assert\NotNull
*/
private array $company_services;
public function __construct(
Id $id,
Inn $inn,
Address $address,
array $company_services,
DateTimeImmutable $date
)
}
public function __invoke(CommandInterface $command): void
{
$company = new Company(
$id = Id::next(),
new Inn($command->getInn()),
new Address(
...
),
$command->getCompanyServices(),
$date = new DateTimeImmutable()
);
$this->repository->add($company);
}
}
public function addCompanyServices($services) {}
Answer the question
In order to leave comments, you need to log in
Persistence by Reachability: Cascade Persist
There are additional semantics that apply to the Cascade Persist operation. During each flush() operation Doctrine detects if there are new entities in any collection and three possible cases can happen:
/**
* @OneToMany(targetEntity="Article", mappedBy="topic", cascade={"persist", "remove"})
*/
private $articles;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question