我就是无法正常工作。我有一个名为“类别”的表:
table name: categories
id
name
和这样的帖子表:
table name: posts
id
category_id
title
body
我正在编写一个控制器/模型/视图以列出category.name和属于at类别的帖子数。我正在崩溃并且正在燃烧该怎么做。这是部分尝试。
$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();
非常感谢任何帮助。搜索了我的stackoverflow,但是看不到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] =>
)
仍然不知道如何获取数组。任何帮助表示赞赏。
答案 0 :(得分:0)
我发现了这一点,这解释了为什么值是空白的:Codeigniter query returning blank
更多文档在这里。 https://www.codeigniter.com/user_guide/database/results.html
因此,这将回显值:
... extension of previous code
$xx = $this->db->get();
print_r($xx->result_array());