为了学习php和codeigniter,我已经开始创建测试网站...类似于博客的东西。UT 这不是重点。我正在使用代码点火器分页来显示我博客的所有帖子。但。。。当我的数据库表(帖子)有超过 14k 个条目时,它开始变慢......而且我不需要这样的回答:"如果它是博客,你永远不会写这么多帖子,那么不要考虑这一点"......我需要真正的解决方案来加快所有这些东西。
这是控制器:
function all()
{
// Pagination $config
$config = $this->m_posts->getPaginationConfig('all', $this->m_posts->getPostsCount());
$this->pagination->initialize($config);
$data['posts'] = $this->m_posts->getAllPosts($config['per_page'], $page);
$data['pagination'] = $this->pagination->create_links();
$this->template->build('posts/posts', $data);
}
型:
function getPaginationConfig($base_url, $total_rows)
{
$config['base_url'] = base_url() . 'posts/'. $base_url;
$config['total_rows'] = $total_rows;
// ----
$config['per_page'] = 10;
$config['num_links'] = 5;
$config['use_page_numbers'] = TRUE;
$config['uri_segment'] = 3;
return $config;
}
function getPostsCount($limit)
{
$this->db->order_by('id', 'desc');
$q = $this->db->get('posts');
return $q->num_rows();
}
function getAllPosts($limit = 0, $start = 0)
{
$this->db->order_by('id', 'desc');
$this->db->where('active', 1);
// Get LATEST posts -> pagination
$q = $this->db->get('posts', $limit, $start);
$array = $q->result_array();
$data = $this->createPostsArray($array);
return $data;
}
function createPostsArray($array)
{
foreach ($array as $key => $row)
{
$array[$key]['usr_info'] = $this->user->getUserData($row['usr_id'], 'nickname');
$this->load->helper('cat_helper');
$array[$key]['cat_ids'] = explodeCategories($row['cat_ids']);
foreach ($array[$key]['cat_ids'] as $numb => $value)
{
$array[$key]['categories'][$numb] = $this->getCategoryName($value);
}
}
return $array;
}
首先,将 getPostsCount 函数更改为
function getPostsCount () {
return $this->db->count_all('posts');
}
你现在这样做的方式是浪费时间/内存/cpu和代码行。
第二件事,使用左/内连接来获取其他数据,而不是在 foreach 语句中抛出一堆查询(这是错误的)。
如果仍需要有关联接内容的帮助,请显示表结构以获取更多帮助。
我认为这个微小的变化,将产生很大的不同。
编辑:
提供更多信息后,下面是包含用户联接的查询(由于不清楚类别的工作原理,因此不包括它)。
function getAllPosts($limit = 0, $start = 0) {
$q = $this->db->select('p.*, u.nickname')
->from('posts p')
->join('users u', 'p.user_id = u.id', 'left')
->limit($limit, $start)
->get();
return $q->result_array();
}
这将返回带有用户昵称的帖子,至于类别,不清楚您如何存储它们,也不清楚爆炸类别在做什么,如果您将它们存储在逗号分隔的字段中,您可以使用单个查询使用 ->where_in('id', array_of_ids);
您需要阅读手册以获取有关如何执行操作的更多帮助:http://ellislab.com/codeigniter/user-guide/