迭代一些字段命令的Doctrine Collection

时间:2009-10-27 18:54:20

标签: php sorting collections doctrine doctrine-1.2

我需要这样的东西:

        $products = Products::getTable()->find(274);
        foreach ($products->Categories->orderBy('title') as $category)
        {
            echo "{$category->title}<br />";
        }

我知道这是不可能的,但是......如果不创建Doctrine_Query,我该怎么做呢?

感谢。

4 个答案:

答案 0 :(得分:31)

你也可以这样做:

$this->hasMany('Category as Categories', array(...
             'orderBy' => 'title ASC'));

在您的架构文件中,它看起来像:

  Relations:
    Categories:
      class: Category
      ....
      orderBy: title ASC

答案 1 :(得分: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 :(得分: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) { /* ... */ }

答案 3 :(得分:4)

您可以向Collection.php添加排序函数:

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

根据年龄对用户集合进行排序将如下所示:

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

}