13

我需要这样的东西:

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

我知道这是不可能的,但是......我怎么能在不创建 Doctrine_Query 的情况下做这样的事情?

谢谢。

4

4 回答 4

31

你也可以这样做:

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

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

  Relations:
    Categories:
      class: Category
      ....
      orderBy: title ASC
于 2010-07-22T18:48:57.193 回答
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);
}
于 2009-11-23T16:20:14.217 回答
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) { /* ... */ }
于 2011-08-25T12:00:40.213 回答
4

您可以在 Colletion.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() );
    }

}
于 2010-08-11T15:36:14.713 回答