Skip to content

Instantly share code, notes, and snippets.

@dominikzogg
Last active December 18, 2015 01:39
Show Gist options
  • Save dominikzogg/5705377 to your computer and use it in GitHub Desktop.
Save dominikzogg/5705377 to your computer and use it in GitHub Desktop.
<?php
namespace Vendor\Bundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Table(name="one")
* @ORM\Entity
*/
class One
{
/**
* @var Many[]|Collection
* @ORM\OneToMany(targetEntity="Many", mappedBy="one", cascade={"persist"})
*/
protected $manies;
public function __construct()
{
$this->manies = new ArrayCollection();
}
/**
* @param Many $many
* @param bool $stopPropagation
* @return $this
*/
public function addMany(Many $many, $stopPropagation = false)
{
$this->manies->add($many);
if(!$stopPropagation) {
$many->setOne($this, true);
}
return $this;
}
/**
* @param Many $many
* @param bool $stopPropagation
* @return $this
*/
public function removeMany(Many $many, $stopPropagation = false)
{
$this->manies->removeElement($many);
if(!$stopPropagation) {
$many->setOne(null, true);
}
return $this;
}
/**
* @param Many[] $manies
* @return $this
*/
public function setManies($manies)
{
foreach($this->manies as $many) {
$this->removeMany($many);
}
foreach($manies as $many) {
$this->addMany($many);
}
return $this;
}
/**
* @return Many[]|Collection
*/
public function getManies()
{
return $this->manies;
}
}
/**
* @ORM\Table(name="many")
* @ORM\Entity
*/
class Many
{
/**
* @var One
* @ORM\ManyToOne(targetEntity="One", inversedBy="manies")
* @ORM\JoinColumn(name="one_id", referencedColumnName="id")
*/
protected $one;
/**
* @param One $one
* @param bool $stopPropagation
* @return $this
*/
public function setOne(One $one = null, $stopPropagation = false)
{
if(!$stopPropagation) {
if(!is_null($this->one)) {
$this->one->removeMany($this, true);
}
if(!is_null($one)) {
$one->addMany($this, true);
}
}
$this->one = $one;
return $this;
}
/**
* @return One
*/
public function getOne()
{
return $this->one;
}
}
@ElectricMaxxx
Copy link

exact that line is a line i have too:
https://gist.github.com/dominikzogg/5705377#file-one2many-php-L49
But my doctrine unfortunately does not recognize all changes i make from the many side. In some situations it works nice, in other not. I am working with sonata admin and take care on the by_reference options, which takes care on add/remove methods.
Would be nice when i understand that, and know when the changes are done.

@dominikzogg
Copy link
Author

@ElectricMaxxx

Its in a very early state, and i will be in 2.0 release, cause BC break:

saxulum-legacy/saxulum-accessor@43a050e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment