Yoan Arnaudov
Yoan Arnaudov

Reputation: 4164

Symfony Doctrine relationships - delete entity on the inverse side

my question is how to delete entity on the inverse side without going through every association and delete it manually.

<?php

/** @Entity */
class User
{
    // ...
    /**
     * @OneToMany(targetEntity="Address", mappedBy="user")
     */
    private $addresses;
    // ...

    public function __construct() {
        $this->addresses = new ArrayCollection();
    }
}

/** @Entity */
class Address
{
    // ...
    /**
     * @ManyToOne(targetEntity="User", inversedBy="features")
     * @JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;
    // ...
}

In this example, Address is the owning side, so I can't delete User because foreign key validation will fail. I have to delete Address and then delete User. If I have 10 relationships like these the delete process is painful.

I can create ManyToMany relationship, but this way the Address entity will have users not user and I want addresses to have only one user.

What is the best way to do this?

Upvotes: 1

Views: 1727

Answers (1)

Farshadi
Farshadi

Reputation: 143

I hope it's helpful. Just add cascade to inverse side entity.

/** @Entity */
class User
{
    // ...
    /**
     * @OneToMany(targetEntity="Address", mappedBy="user", cascade={"persist", "remove"})
     */
    private $addresses;
    // ...

    public function __construct() {
        $this->addresses = new ArrayCollection();
    }
    /*
     * @return ArrayCollection
     */
    public function getAddresses (){
       return $this->addresses:
    }

    /*
     * @pram Address $address
     */
    public function setAddresses (Address $address){
       $this->addresses->add ($address);
    }
}

Upvotes: 2

Related Questions