2017-04-11 40 views
1

(使用cascade=persist)的獨立實體調用persist()flush()之前我做多次調用$this->myDependentEntityCollection[] = $myDependentEntity;(即它的類型ArrayCollectionPersistentCollection學說2的ArrayCollection :: Add()方法仍然存在項目以相反的順序

但是,集合中的依賴實體的保存順序與它們添加的順序相反(我猜他們使用堆棧,然後逐個彈出項目)。

以下面的示例爲例OrderItem1:N的關係:

// Order.php 
/* (...doctrine stuff..., cascade={"persist"}) */ 
protected $items; 

public function addItem(Item $item) { 
    $item->setOrder($this); 
    $this->items[] = $item; 
} 

// Item.php 
public function setOrder(Order $order) { 
    $this->order = $order; 
} 

// Somewhere else in the code 
$order->addItem($item1); 
$order->addItem($item2); 
$order->addItem($item3); 

$em->persist($order); 
$em->flush(); 

他們得到持續的順序item3item2item1;而不是1,2,3

我該如何使它們以正確的順序保存?

+0

你可以嘗試排序之前堅持.... – Matteo

+0

@Matteo我想這種做法。不知道如何排序ArrayCollection。 –

+0

有點偏題,但它有關係嗎?我一直認爲我們不應該依賴數據庫中記錄的順序。當您檢索這些項目時,應該設置這些項目的順序IMO。儘管如此,有趣的問題。 – Veve

回答

1

嘗試使用array_unshift

array_unshift - 在前置的一個或多個元素添加到 陣列

如實施例的開頭:

public function addItem(Item $item) { 
    $item->setOrder($this); 
    array_unshift($this->items, $item); 
} 

希望這有助於

注意:

正如評論克里斯托弗·弗朗西斯科說,是不是不可能性到的ArrayCollection對象傳遞給array_unshift功能,這樣一招可以是以下:

public function addItem(Item $item) { 
    $item->setOrder($this); 
    $itemsAsArray = $this->items->toArray(); 
    array_unshift($itemsAsArray, $item); 
    $this->items = new ArrayCollection($itemsAsArray); 
} 

否則,你可以實現對象的方法即inverse數組的順序並在持續之前調用它,但更容易出錯(您可能忘記調用該方法)。

+0

注意'$ this-> items'實際上是一個'ArrayCollection',而不是'array',這仍然可以工作嗎? –

+0

嗨@ChristopherFrancisco你是對的!我使用解決方法更新我的答案 – Matteo