2016-12-31 6 views
0
$categories = PostCategoryQuery::create()->find(); 

    $categories_array = []; 
    foreach ($categories as $k => $category): 
     $posts_count = PostQuery::create()->filterByPostCategory($category)->count(); 
     $categories_array[$k]['category'] = $category->getName(); 
     $categories_array[$k]['count'] = $posts_count; 
    endforeach; 

    uasort($categories_array, "sortByCount"); 

    function sortByCount($a, $b) { 
     return $a['count'] > $b['count'] ? -1 : 1; 
    } 

私はそれに関連する記事の数によって「カテゴリ」の配列順序を取得したい、私はいくつかの提案を得ることを望ん、私のコードを短くする方法が必要だと思い、感謝〜これらのコードを短縮するにはどうすればよいですか?あなたのORMで

+0

あなたはどのバージョンのPHPを使用していますか? –

+0

@RossWilson PHP7 with Propel 2.0 – zjuwujunchao

答えて

1

場合は、 ...単に

select category, count(*) 
    from post_category 
    inner join post on post_category.category_id = post.category_id 
    group by category 
    order by count(*) 

のような選択を行うことができ、その後、あなたのコードは、クエリに削減されるあなたによってグループで

0

を単純なクエリを使用することができ、私は正確にあなたのモデルを知らないが、私は希望次のようなものをお勧めします:

$categories_array = PostQuery::create('pq') 
    ->joinPostCategory('pc') 
    ->withColumn('COUNT(pq.id)', 'count') 
    ->groupBy('pc.id') 
    ->select(array('pc.name', 'count')) 
    ->orderBy('count') 
    ->find(); 

// Should return PropelArrayCollection(
// array('pc.name' => 'category1', 'count' => 123), 
// array('pc.name' => 'category2', 'count' => 234) 
//) 

このようにして、必要な列のみを選択するので、オブジェクトの水分補給を避けることができます。

関連する問題