2016-09-22 44 views
3

我在產品和其子圖像之間建立了關係。一個正常的一對多關聯。在Symfony中爲兒童一對多過濾器添加排序

用下面的代碼我得到的子圖像中的對象:

$product->getImages(); 

的我想通過圖像步行到修改的東西,我這樣做有:

foreach ($product->getImages() as $Image) { 
      // do something 
     } 

只有圖像有一個名爲seq的字段。什麼是代表圖像順序的數字。我如何訂購與seq編號相關的對象?

謝謝!

+1

[ 「usort」 學說\ COMMON \收藏的可能的複製\ ArrayCollection的?](http://stackoverflow.com/questions/16705425/usort-a-doctrine-common-collections-arraycollection) – jcroll

回答

3

您必須爲此使用註釋@orderBy。請使用類似

<?php 
/** @Entity **/ 
class Product 
{ 
    /** 
    * @OneToMany(targetEntity="Image") 
    * @OrderBy({"seq" = "ASC"}) 
    **/ 
    private $images; 
} 
0

你可以在教義關係添加批註(但這對您對集合中的所有接入影響,你不能執行另一排序方法)可以實現使用學說標準(參見一些示例here)在產品實體本身中的自定義過濾器。

如例:

class Product 
{ 
    /** 
    * @OneToMany(targetEntity="Image") 
    **/ 
    private $images; 

public function __construct() 
{ 
    $this->images = new ArrayCollection(); 
} 

public function getSortedImages() 
{ 
    $expr = Criteria::expr(); 

    $criteria = Criteria::create() 
     ->where($expr->neq('seq', null)) // Analog to IS NOT NULL 
     ->orderBy(array('seq'=>'DESC')); 

    return $this->images->matching($criteria); 
} 

} 

希望這有助於

對於簡單的情況下發表@Liju PM的解決方案是好的