添加方法不能在多对多的关系中工作
我有这种巴士和司机之间的多对多关系。添加方法不能在多对多的关系中工作
这是公交实体:
/**
* @var ArrayCollection<Driver> The driver of this bus.
* @ORM\ManyToMany(targetEntity="Driver", inversedBy="bus" , cascade={"persist"})
* @ORM\JoinTable(name="bus_driver")
* @ORM\JoinColumn(name="driver_id", referencedColumnName="id")
* */
private $driver;
public function __construct() {
$this->driver = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addDriver($driver) {
$this->driver[] = $driver;
return $this;
}
这是驱动程序实体:
/**
* @var ArrayCollection<Bus> The buses of this driver
* @ORM\ManyToMany(targetEntity="Bus", mappedBy="driver")
* @ORM\JoinTable(name="bus_driver")
* @ORM\JoinColumn(name="bus_id", referencedColumnName="id")
*/
private $bus;
public function __construct() {
$this->bus = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addBus($bus) {
$this->bus[] = $bus;
$bus->addDriver($this);
return $this;
}
我的问题是,当我加总线驱动的关系依然存在,但不是当我加了一辆公共汽车的司机。它只能从公共汽车一侧运行。
请考虑重命名$驱动程序到$驱动程序,因为有多个驱动器(同为总线 - >总线)
,然后你应该试试:
@ORM \多对多(targetEntity =” XXX”,级联= { “坚持”})
改变这些(加空,称之为 '驱动程序'):
use Doctrine\Common\Collections\ArrayCollection;
...
private $drivers = null;
public function __construct() {
$this->drivers = new ArrayCollection();
}
public function addDriver($driver) {
$this->drivers[] = $driver;
return $this;
}
此外,为了解决从巴士实体侧的问题,您可能(但我不知道)需要这种变化:
public function addDriver($driver) {
$driver->addBus($this);
$this->drivers[] = $driver;
return $this;
}
试试吧,因为我在一个多对一的关系也有类似的情形,我想知道上述更改是否可行。
添加方法似乎并没有被触发,它只适用于当我命名它setDriver例如 –
检查我的答案:))它适用于我多达许多和一对多 –
唯一的工作场景是当我有:
驱动程序集合的setter。 一个addDriver方法。 removeDriver方法。
如果我删除了其中的一个,那么addDriver根本就不会触发。
要完成这个答案,如果你使用ArrayCollection,使用'add()'方法将一个元素添加到一个集合 – ceadreak
我试过了,但仍然无法正常工作,addSomthings方法没有被post操作触发。 工作的唯一的东西是: 公共功能setDrivers($ driver){ $ this-> driver = $ driver; return $ this; } 这只适用于拥有一方(巴士)。 –