1

我在 phalcon volt 中有一个计数问题。我有一个名为的表category,我有两列idcname,还有一个表 blog 和一列category。我想显示每个类别中有多少帖子。
当我将帖子插入博客表时,在类别列中我插入其类别id。首先,我只是检索所有类别的列表,如下所示:

[controller]
$categories = Category::find();
$this->view->setVar('category', $categories);
$cx = Blogs::find();
$this->view->setVar('cates',$cx);

[Volt]
{% for categories in category %}
<a href="blog/category/{{categories.cname}}" class="tags">{{ categories.cname }} 
<span>[ 
{% for cx in cates %}
    {%if cx.category === categories.id %}
        <?php echo(count($cx->category)); ?>
    {% endif %}
{% endfor %}
]</span></a>
{% endfor %}

它的呈现像“1 1 1”或“1 1”或“1”,但它应该呈现像“3”或“2”或“1”我错了什么?

我也尝试过这样但没有得到预期的输出:

{% for categories in category %}
<a href="blog/category/{{categories.cname}}" class="tags">{{ categories.cname }} 
<span>[ 
{% for cx in cates %}

{%if cx.category === categories.id %}
{% if loop.first %} {{ loop.length }} {% endif %}

{% endif %}

{% endfor %}
]</span></a>
{% endfor %}
4

2 回答 2

1

您是否在 Phalcon 中定义了模型之间的关系?如果是这样,您可以使用内置命令查询每个类别的帖子总数

文档中的示例:

您还可以使用“count”前缀返回一个整数,表示相关记录的计数:

$robot = Robots::findFirst(2);
echo "The robot has ", $robot->countRobotsParts(), " parts\n";

我对 Volt 模板没有太多经验,但我想它会是这样的:

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

参考:https ://docs.phalconphp.com/en/latest/reference/models.html#taking-advantage-of-relationships

更新 - 模型关系

[型号:类别]

public function initialize()
{
    // id => primary key name of the Category table
    // Blogs => name of the table you want to create a relationship with
    // category => name of the foreign key column in your relationship table
    $this->hasMany('id', 'Blogs', 'category');
}

[模型:博客]

public function initialize()
{
    // category => blog column name which refers to the ID in the Category table
    // Category => name of the Category table
    // id => name of the primary key column in the Category table
    $this->belongsTo('category', 'Category', 'id');
}
于 2016-04-10T11:31:48.773 回答
0

不,先生,它不工作。但我只是这样解决了我的问题:

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

[volt]

{% for categories in category %}
<a href="blog/category/{{categories.cname}}" class="tags">{{ categories.cname }} 
<span>[ 
<?php 
$catcount = $this->modelsManager->executeQuery("SELECT Blogs.category FROM Blogs WHERE Blogs.category = $categories->id");echo(count($catcount));
?>
]</span></a>
{% endfor %}

现在它按预期工作。在这里我不做任何关系离子模型。可以吗,先生。请!谢谢

于 2016-04-11T04:23:23.397 回答