Hi I have the following class
namespace MP\\User\\RegistrationBundle\\Entity;
use Doctrine\\ORM\\Mapping as ORM;
use
I tried the answers above, but got the same foreign key constraint violation.
My code was something like the following:
class FooBar
{
/**
* @ORM\OneToMany(
* targetEntity="Foo",
* mappedBy="foobar",
* cascade={"persist", "remove"},
* orphanRemoval=true
* )
* @var Collection|Foo[]
*/
private $fooCollection;
/**
* @return Collection|Foo[]
*/
public function getFooCollection()
{
return $this->fooCollection;
}
/**
* @param Collection|Foo[] $fooCollection
*
* @return $this
*/
public function setFooCollection($fooCollection): FooBar
{
$this->fooCollection = $fooCollection;
return $this;
}
}
class Foo
{
// ... some more properties & ID here ....
/**
* @ORM\OneToMany(
* targetEntity="Bar",
* mappedBy="foo",
* cascade={"persist", "remove"},
* orphanRemoval=true
* )
* @var Collection|Bar[]
*/
private $barCollection;
/**
* @ORM\ManyToOne(
* targetEntity="FooBar",
* inversedBy="fooCollection"
* )
* @ORM\JoinColumn(
* name="fooBarId",
* referencedColumnName="fooBarId",
* nullable=false
* )
* @var FooBar
*/
private $fooBar;
public function __construct()
{
$this->barCollection = new ArrayCollection();
}
/**
* @return Bar[]|Collection
*/
public function getBarCollection()
{
return $this->barCollection;
}
/**
* @param Bar[]|Collection $barCollection
*
* @return $this
*/
public function setBarCollection($barCollection): Foo
{
$this->barCollection = $barCollection;
return $this;
}
/**
* @return FooBar
*/
public function getFooBar(): FooBar
{
return $this->fooBar;
}
/**
* @param FooBar $fooBar
*
* @return $this
*/
public function setFooBar(FooBar $fooBar): Foo
{
$this->fooBar = $fooBar;
return $this;
}
// ... some more getters & setters here ...
}
class Bar
{
// ... some more properties & ID here ....
/**
* @ORM\ManyToOne(
* targetEntity="Foo",
* inversedBy="barCollection"
* )
* @ORM\JoinColumn(
* name="fooId",
* referencedColumnName="fooId",
* nullable=false
* )
* @var Foo
*/
private $foo;
// ... some more getters & setters here ...
}
I had another part of the program, where I tried to remove all Foo's corresponding to a FooBar, with the following code.
$fooBar = new FooBar();
$fooBar->setFooCollection([]);
$entityManager->persist($foorBar);
$entityManager->flush();
This gave an foreign key exception on the relationship between Foo and Bar "Cannot delete or update a parent row: a foreign key constraint fails".
Adding the following method to FooBar:
/**
* @param Foo[] $collection
*/
public function removeFooCollection($collection)
{
/** @var Foo $entry */
foreach ($collection as $entry)
{
$this->fooCollection->removeElement($entry);
$entry->setFooBar(null);
}
}
And using the following code to remove all Foo's related to the FooBar:
$fooBar->removeFooCollection(
$fooBar->getFooCollection()
);
$entityManager->persist($fooBar);
$entityManager->flush();
Fixed all foreign key constraint issues.