简体   繁体   English

Codeigniter在列出类别时统计一个类别中的文章数

[英]Codeigniter count number of articles in one category while listing categories

I have some problem while listing categories from database. 从数据库列出类别时遇到一些问题。

First i have a table called "Videos" where i store som videos-information like v_name, v_description and category_name. 首先,我有一个名为“视频”的表,用于存储诸如v_name,v_description和category_name之类的som视频信息。

In the second table called "Categories" where i store categories-information like c_name and c_description. 在称为“类别”的第二张表中,我存储了诸如c_name和c_description之类的类别信息。

OFC i have id's in every table :) 我在每个表中都有ID的OFC :)

But now i want to list the categories and in the same query count every videoitem in every category. 但是现在我要列出类别,并在同一查询中计算每个类别中的每个视频项目。

This is the code and i can't figure out how to do in the model now and later how to show the numbers in the view file, so pleace help me! 这是代码,我现在不知道如何在模型中进行操作,以后又无法在视图文件中显示数字,所以请帮帮我!

Thanks for your time and support :D 感谢您的时间和支持:D

    $this->db->select('c.*');
    $this->db->from('categories as c');
    $this->db->join('videos as v', 'c.c_name = v.v_category', 'right');
    return $this->db->get()->result_array();

For your code to work you need two changes: 为了使代码正常工作,您需要进行两项更改:

  • First you join type should be a "left join". 首先,您的联接类型应为“左联接”。 Than way you still will get a count result (0) even if a category has no videos yet. 即使类别没有视频,您仍然可以得到计数结果(0)。
  • Second you need to group your results to be able to use the aggregate function count(). 其次,您需要对结果进行分组,以便能够使用聚合函数count()。

Try with this: 试试这个:

$this->db
->select('categories.c_name, COUNT(videos.id) as num_videos')
->from('categories')
->join('videos', 'categories.c_name = videos.v_category', 'left')
->group_by('categories.c_name');

Also you should reconsider your DB design. 另外,您应该重新考虑数据库设计。 If you have id columns in both tables (wich I assume are the primary key) then you should define the relationship between the tables (foreign keys) using the id column, not the name. 如果两个表中都有ID列(我假设是主键),则应使用ID列而不是名称来定义表(外键)之间的关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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