質問

次のようなものが必要です:

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

不可能であることはわかっていますが、... Doctrine_Queryを作成せずにこのようなことを行うにはどうすればよいですか?

ありがとう。

役に立ちましたか?

解決

私はちょうど同じ問題を見ていました。 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);
}

他のヒント

次のこともできます。

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

スキーマファイルでは次のようになります。

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

コレクションイテレータを使用できます:

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

Collection.phpにソート関数を追加できます:

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

年齢によるユーザーのDoctrineコレクションのソートは次のようになります。

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

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top