迭代主义下令收集一些领域(Iterate Doctrine Collection ordered b

2019-09-01 16:36发布

我需要的是这样的:

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

我知道这是不可能的,但是...我怎么能这样做而无需创建一个Doctrine_Query?

谢谢。

Answer 1:

我只是在看同样的问题。 您需要将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);
}


Answer 2:

你也可以这样做:

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

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

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


Answer 3:

你可以使用集合迭代器:

$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) { /* ... */ }


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

}


文章来源: Iterate Doctrine Collection ordered by some field