我创建了一个函数来计算基于下面2个db表的帖子总数
1-帖子:
post_id user_id
=========== ====
61 122
62 122
96 122
97 122
98 122
2- post_meta:
meta_id post_id status
======== ======= ======
1 61 1
2 62 0
3 62 1
4 91 1
5 97 1
6 98 1
因为user_id存在于帖子表中,而两个表上的唯一标识符是 post_id 我想查看status = 1和user_id = $ user_id的所有帖子 到目前为止我的模型功能
/**
* The function get_all_user_post_count gets all count posts for admin dashboard
*
* @return array with posts or false
*/
public function get_all_user_post_count($user_id) {
$this->db->select('network_name,COUNT(meta_id) as number', false);
$this->db->from('posts_meta');
$this->db->join('posts', 'posts_meta.post_id=posts.post_id', 'left');
$this->db->where(['status' => '1', 'user_id' => $user_id]);
$this->db->group_by('network_name');
$this->db->order_by('network_name');
$query = $this->db->get();
if ($query->num_rows() > 0) {
$result = $query->result();
// Create new array
$new_array = [];
foreach ($result as $data) {
$new_array[$data->network_name] = $data->number;
}
return $new_array;
} else {
return false;
}
}
这是我到目前为止的控制器功能
// Count all sent posts per social network
$count_sent_posts = $this->posts->get_all_user_post_count($this->user_id);
$this->footer = [
'statistics' => $statistics,
'sent' => $count_sent_posts
];
$this->user_layout();
发生数据库错误错误号:1052
列'状态' in where子句不明确
SELECT network_name,COUNT(meta_id)as number FROM
posts_meta
LEFT 加入posts
posts_meta
。post_id
=posts
。post_id
WHEREstatus
=' 1'和user_id
=' 118' GROUP BYnetwork_name
ORDER BYnetwork_name
文件名:models / Posts.php
行号:393
答案 0 :(得分:1)
试试这一个=>
public function get_all_user_post_count($user_id) {
$where = array('posts_meta.status ' => 1 , 'posts.user_id ' => $user_id);
$this->db->select('posts_meta.network_name,COUNT(posts_meta.meta_id) as number', false);
$this->db->from('posts_meta');
$this->db->join('posts', 'posts_meta.post_id=posts.post_id', 'left');
$this->db->where($where);
$this->db->group_by('posts_meta.network_name');
$this->db->order_by('posts_meta.network_name');
$query = $this->db->get();
if ($query->num_rows() > 0) {
$result = $query->result();
// Create new array
$new_array = [];
foreach ($result as $data) {
$new_array[$data->network_name] = $data->number;
}
return $new_array;
} else {
return false;
}
}