Frage

Ich brauche etwas wie folgt aus:

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

ich weiß, ist es nicht möglich, aber ... Wie kann ich etwas tun, ohne eine Doctrine_Query erstellen?

Danke.

War es hilfreich?

Lösung

Ich habe gerade auf dem gleichen Problem. Sie müssen die Doctrine_Collection in ein Array konvertieren:

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

Dann können Sie eine benutzerdefinierte Sortierfunktion erstellen und nennen es:

// sort children
usort($children, array(__CLASS__, 'compareChildren')); // fixed __CLASS__

Wo compareChildren sieht etwa so aus:

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

Andere Tipps

Sie können auch tun:

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

In Ihrer Schemadatei es wie folgt aussieht:

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

Sie könnten Sammlung Iterator verwenden:

$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
}

Wenn Sie Sammlung mit __toString Methode sortieren wollen, wird es viel einfacher sein:

foreach ($collection->getIterator()->asort() as $element) { /* ... */ }

Sie können eine Sortierfunktion Colletion.php hinzufügen:

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

ein Doctrine_Collection der Nutzer Sortieren nach ihrem Alter würde wie folgt aussehen:

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

}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top