1

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?

3
  • You can make DB foreign key with option ondelete=cascade, so DB will delete all childs automatically. Commented Oct 18, 2016 at 8:56
  • Wo where should I put the onDelete? on the ManyToOne relationship? Commented Oct 18, 2016 at 9:02
  • docs.doctrine-project.org/projects/doctrine-orm/en/latest/… Commented Oct 18, 2016 at 9:05

1 Answer 1

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.