按照某个字段对Doctrine集合进行迭代排序

13
我需要类似于这样的东西:
        $products = Products::getTable()->find(274);
        foreach ($products->Categories->orderBy('title') as $category)
        {
            echo "{$category->title}<br />";
        }
我知道这似乎不可能,但是……如果不创建Doctrine_Query,我该怎么做类似的事情呢?
谢谢。
4个回答

31

您也可以这样做:

$this->hasMany('Category as Categories', array(...
             'orderBy' => 'title ASC'));
在您的模式文件中,它看起来像是:
  Relations:
    Categories:
      class: Category
      ....
      orderBy: title ASC

5
如果排序是“永久性的”,使用这种方法比使用Chris William的方法要好得多。 - avetisk
2
缺点是永久性的。为此关系的每个查询添加orderBy将影响性能。 - Mike Purcell
或通过@OrderBy注释:http://docs.doctrine-project.org/en/2.0.x/reference/annotations-reference.html#annref-orderby - zizoujab

9

我正在看这个问题。您需要将Doctrine_Collection转换为数组:

$someDbObject = Doctrine_Query::create()...;
$children = $someDbObject->Children;
$children = $children->getData(); // convert from Doctrine_Collection to array

然后,您可以创建一个自定义排序函数并调用它:
// sort children
usort($children, array(__CLASS__, 'compareChildren')); // fixed __CLASS__

其中 compareChildren 大致如下:

private static function compareChildren($a, $b) {
   // in this case "label" is the name of the database column
   return strcmp($a->label, $b->label);
}

2
你的解决方案只有在我将它更改为以下内容时才有效:usort($children, array(CLASS, 'compareChildren')); - stoefln

9
您可以使用集合迭代器:
$collection = Table::getInstance()->findAll();

$iter = $collection->getIterator();
$iter->uasort(function($a, $b) {
  $name_a = (int)$a->getName();
  $name_b = (int)$b->getName();

  return $name_a == $name_b ? 0 : $name_a > $name_b ? 1 : - 1;
});        

foreach ($iter as $element) {
  // ... Now you could iterate sorted collection
}

如果你想使用__toString方法对集合进行排序,那么这将变得更加容易:
foreach ($collection->getIterator()->asort() as $element) { /* ... */ }

1
尝试使用$collection->getIterator()->asort(),但它只返回布尔值。 - Mike Purcell
抱歉,我忘记它是如何工作的了。你说得对,它在成功时返回true,在失败时返回false。这是一个非常好的设计。 - temochka
如果在迭代之前调用asort,那么您很有可能能够遍历排序后的列表。 - Mike Purcell

4

你可以在 Collection.php 中添加一个排序函数:

public function sortBy( $sortFunction )
{
    usort($this->data, $sortFunction);
}  

对用户的Doctrine_Collection按年龄进行排序的代码如下:

class ExampleClass
{

    public static function sortByAge( $a , $b )
    {
         $age_a = $a->age;
         $age_b = $b->age;

         return $age_a == $age_b ? 0 : $age_a > $age_b ? 1 : - 1;
    }    

    public function sortExample()
    {
         $users = User::getTable()->findAll();
         $users ->sortBy('ExampleClass::sortByAge');

         echo "Oldest User:";
         var_dump ( $users->end() );
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接