简体   繁体   中英

phalcon count by id in volt

I'm facing problem in Phalcon. in my blog i have a category table there have all list of category like "a,b,c,d,e,f,g,h,i" and in my blog table have a column name category. in category column i'm inserting the id of category. now the problem is i want to count how many post have in each category. i'm unable to get expected result. count result result shows me result [0]. whats my fault?

[Blog Controller]

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

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

[Index View]

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

You would benefit from using Model Relationships as referenced here: https://docs.phalconphp.com/uk/latest/reference/models.html#relationships-between-models

Essentially your category model could look like this:

<?php

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

Then to get a count of articles per category, do something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM