sajad torkamani

When you use Symfony’s make:entity command and add a relation, you’ll be asked a question like this:

Do you want to automatically deleted <SomeEntity> objects (orphanRemoval)?

But what does that question mean in plain English?

Your answer to that question determines whether the orphanRemoval attribute on the parent entity has orphanRemoval: true or orphanRemoval: falsel.

If you answer yes, you’d get something like this:

class Company
{
    #[ORM\OneToMany(
        mappedBy: 'company',
        targetEntity: CommercialAgreementTemplate::class,
        orphanRemoval: true
    )]
    private Collection $commercialAgreementTemplates;
}

If you answer no, orphanRemoval will be false:

class Company
{
    #[ORM\OneToMany(
        mappedBy: 'company',
        targetEntity: CommercialAgreementTemplate::class,
        orphanRemoval: false
    )]
    private Collection $commercialAgreementTemplates;
}

So the question is what does orphanRemoval: true do? To understand, let’s assume we have the following two entities:

Company

class Company
{
    #[ORM\OneToMany(
        mappedBy: 'company',
        targetEntity: CommercialAgreementTemplate::class,
        orphanRemoval: true
    )]
    private Collection $commercialAgreementTemplates;
}

CommercialAgreementTemplate

class CommercialAgreementTemplate
{
    #[ORM\ManyToOne]
    private ?Company $company = null;
}

Given those entities, if we remove a CommercialAgreementTemplate from a Company record like so:

$company->removeCommercialAgreementTemplate($template);

This is how Doctrine’s behaviour will differ based on the orphanRemoval setting:

orphanRemoval: trueDoctrine will see that $template is no longer attached to a Company record so it’s considered an “orphan”. Because orphanRemoval is true, Doctrine will remove that orphan record from the database with a query like DELETE FROM commercial_agreement_template WHERE id = <id>.
orphanRemoval: falseAlthough $template is an “orphan” record, Doctrine will not remove the orphan because orphanRemoval is false. Instead, it’ll just update the foreign key reference with a query like: UPDATE commercial_agreement_template SET company_id = NULL where id <id>.

So in short, that question from the make:entity command determines whether the owning entity will have the orphanRemoval attribute set to true or false for a relation field. That in turn determines what happens when the relation record is orphaned.

Tagged: Doctrine