سؤال

وأنا بحاجة إلى شيء من هذا القبيل:

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

هل يمكن إضافة وظيفة الفرز ل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() );
    }

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top