如何缩短这些代码?

时间:2016-12-31 15:53:46

标签: php mysql propel

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

我想通过相关帖子的数字获得'类别'数组顺序,我认为必须有一种方法可以缩短我的代码,希望得到一些建议,谢谢〜

2 个答案:

答案 0 :(得分:1)

如果在你的ORM中你可以使用一个简单的查询分组,你就可以执行像

这样的选择
    select category, count(*)
    from  post_category 
    inner join post  on post_category.category_id = post.category_id
    group by category
    order by count(*)

然后您的代码将缩减为查询..

答案 1 :(得分: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)
// )

这样可以避免对象保湿,因为您只选择所需的列。

相关问题