phalcon按id计算

时间:2016-09-28 09:16:21

标签: php count phalcon volt

我在Phalcon遇到问题。在我的博客中我有一个类别表,其中包含所有类别列表,如“a,b,c,d,e,f,g,h,i”,并且在我的博客表中有一个列名类别。在类别列中我插入了类别的ID。现在问题是我想计算每个类别中有多少帖子。我无法得到预期的结果。计数结果显示结果[0]。我的错是什么?

[博客控制器]

    $categories = Category::find();
    $this->view->setVar('category', $categories);

    $ab = Blogs::countBycategory($categories->id);
    $this->view->setVar('ccat',$ab);

[索引视图]

    {% for categories in category %}
    <a title="{{categories.cname}}" href="blog/category/{{categories.cname}}" class="tags">
        {{ categories.cname }} <span>[ {{ccat}} ]</span></a>
    {% endfor %}

1 个答案:

答案 0 :(得分:1)

您可以从使用此处引用的模型关系中受益: https://docs.phalconphp.com/uk/latest/reference/models.html#relationships-between-models

基本上你的类别模型可能如下所示:

<?php

class Category extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasMany("id", "Blogs", "category_id", [
            "alias" => "articles"
        ]);
    }
}

然后要获得每个类别的文章计数,请执行以下操作:

$categories = Category::find();
foreach($categories as $category) {
    echo $category->cname . " " . count($category->articles) . "\n";
}