命令我需要的是這樣的:迭代主義系列有些外地
$products = Products::getTable()->find(274);
foreach ($products->Categories->orderBy('title') as $category)
{
echo "{$category->title}<br />";
}
我知道是不可能的,但是...我怎麼能這樣做而無需創建一個Doctrine_Query?
謝謝。
命令我需要的是這樣的:迭代主義系列有些外地
$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
你可能會添加排序功能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());
}
}
您可以使用集合迭代器:
$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-> getIterator() - > asort()',但它只是返回布爾值。 –
對不起,我忘了它是如何工作的。你是對的,它在成功時返回真實,在失敗時返回錯誤。這樣一個不錯的設計。 – temochka
如果您在迭代之前調用asort,則可能會遍歷排序列表。 –
您的解決方案,只有當我改成了工作: usort($孩子,陣列(_____ CLASS_____, 'compareChildren') ); – stoefln