我在phalcon伏特中有计数问题。我有一个名为category
的表,我有两列id
和cname
,还有一个表博客,还有一列category
。我想表明每个类别中有多少帖子
当我在博客表中插入帖子时,在类别列I中插入其类别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 %}
它的渲染类似于&#34; 1 1 1&#34;或&#34; 1 1&#34;或&#34; 1&#34;但它应该呈现像&#34; 3&#34;或&#34; 2&#34;或&#34; 1&#34;我的错了什么?
我也尝试了这样但没有得到预期的输出:
{% 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 %}
答案 0 :(得分: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');
}
[model:Blogs]
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');
}
答案 1 :(得分: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 %}
现在按预期工作。在这里,我不做任何关系离子模型。是的,先生。请!日Thnx