我只是无法做到这一点。 我有一个名为类别的表格,如下所示:
table name: categories
id
name
还有一个帖子表,如下所示:
table name: posts
id
category_id
title
body
我正在编写一个控制器/模型/视图来列出属于 at 类别的 category.name 和帖子数量。 我正在崩溃和燃烧如何做到这一点。 这是部分尝试。
$this->db->select('
posts.*,
categories.*,
COUNT(posts.category_id) as num_posts
');
$this->db->from('posts');
$this->db->join('categories', 'categories.id = posts.category_id');
$xx = $this->db->get();
echo '<pre>';
print_r($xx);
echo '</pre>';
exit();
任何帮助非常感谢。 已经搜索了我的堆栈溢出,但看不到CI3解决方案。
新更新。 此 sql 工作:
SELECT
categories.id,
categories.name,
Count(posts.id) as cnt
FROM
categories
LEFT JOIN
posts
ON
categories.id=posts.category_id
GROUP BY
categories.name
当我运行它时,我得到低于这是我期望的:
id name cnt
---------------------------------------------
80 | 24354234234 | 2
76 | Associations and Organizations | 9
但是当我像这样更改为活动记录时:
$this->db->select('categories.id, categories.name, COUNT(posts.id) as num_posts');
$this->db->from('categories');
$this->db->join('posts', 'categories.id = posts.category_id');
$this->db->group_by('categories.name');
$xx = $this->db->get();
我print_r($xx(并且看不到我的任何数据。 这就是我得到的:
CI_DB_mysqli_result Object
(
[conn_id] => mysqli Object
(
[affected_rows] => 2
[client_info] => 5.5.59
[client_version] => 50559
[connect_errno] => 0
[connect_error] =>
[errno] => 0
[error] =>
[error_list] => Array
(
)
[field_count] => 3
[host_info] => Localhost via UNIX socket
[info] =>
[insert_id] => 0
[server_info] => 5.5.58-0ubuntu0.14.04.1
[server_version] => 50558
[stat] => Uptime: 7546485 Threads: 2 Questions: 523149 Slow queries: 0 Opens: 257 Flush tables: 1 Open tables: 200 Queries per second avg: 0.069
[sqlstate] => 00000
[protocol_version] => 10
[thread_id] => 42310
[warning_count] => 0
)
[result_id] => mysqli_result Object
(
[current_field] => 0
[field_count] => 3
[lengths] =>
[num_rows] => 2
[type] => 0
)
[result_array] => Array
(
)
[result_object] => Array
(
)
[custom_result_object] => Array
(
)
[current_row] => 0
[num_rows] =>
[row_data] =>
)
仍然不知道如何获取数组。 任何帮助表示赞赏。
我发现这解释了为什么值为空: 代码点火器查询返回空白
更多文档在这里。 https://www.codeigniter.com/user_guide/database/results.html
因此,这将回显以下值:
... extension of previous code
$xx = $this->db->get();
print_r($xx->result_array());