2016-06-08 237 views
0

我有這種巴士和司機之間的多對多關係。添加方法不能在多對多的關係中工作

這是公交實體:

/** 
    * @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; 
    } 

我的問題是,當我加總線驅動的關係依然存在,但不是當我加了一輛公共汽車的司機。它只能從公共汽車一側運行。

回答

0

請考慮重命名$驅動程序到$驅動程序,因爲有多個驅動器(同爲總線 - >總線)

,然後你應該試試:

@ORM \多對多(targetEntity =」 XXX」,級聯= { 「堅持」})

更多細節:http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/working-with-associations.html#transitive-persistence-cascade-operations

+0

要完成這個答案,如果你使用ArrayCollection,使用'add()'方法將一個元素添加到一個集合 – ceadreak

+0

我試過了,但仍然無法正常工作,addSomthings方法沒有被post操作觸發。 工作的唯一的東西是: 公共功能setDrivers($ driver){ $ this-> driver = $ driver; return $ this; } 這隻適用於擁有一方(巴士)。 –

0

改變這些(加空,稱之爲 '驅動程序'):

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; 
} 

試試吧,因爲我在一個多對一的關係也有類似的情形,我想知道上述更改是否可行。

+0

添加方法似乎並沒有被觸發,它只適用於當我命名它setDriver例如 –

+0

檢查我的答案:))它適用於我多達許多和一對多 –

0

唯一的工作場景是當我有:

驅動程序集合的setter。 一個addDriver方法。 removeDriver方法。

如果我刪除了其中的一個,那麼addDriver根本就不會觸發。

相關問題