我在博客模块
的tagged()方法之后构建了这个方法public function genres($genre = null)
{
$this->db->order_by('name', 'ASC');
$result = $this->db->get('keywords');
$genres = $result->result();
if($genre)
{
$this->load->model('genres_m');
// decode encoded cyrillic characters
$genre = rawurldecode($genre) OR redirect('generos');
$time[] = time();
// Count total blog posts and work out how many pages exist
$pagination = create_pagination(lang('ebooks:routes:genres') . '/' . $genre, $this->genres_m->count_genres_by($genre, array('entry_active' => 1)), NULL, 4);
$time[] = time();
// Get the current page of blog posts
$books = $this->genres_m
->limit($pagination['per_page'])
->order_by('info_title', 'ASC')
->get_genres_by($genre, array('entry_active' => 1));
$time[] = time();
foreach ($books AS &$book)
{
$book->books_info_genre = Keywords::get($book->books_info_genre, 'blog/tagged');
$book->url = site_url(lang('ebooks:routes:ebook') . '/' . $book->info_title . '/' . $book->id);
}
$time[] = time();
// Set meta description based on post titles
//$meta = $this->_posts_metadata($books);
$name = str_replace('-', ' ', $genre);
// Build the page
$this->template
->title($this->_template_title(lang('ebooks:of').' '.$name))
->set_metadata('description', $this->_template_title(lang('ebooks:of').' '.$name))
->set_metadata('keywords', $this->_template_title(lang('ebooks:of').' '.$name))
->set('genres', $genres)
->set('books', $books)
->set('genre', $genre)
->set('time', $time)
->set('pagination', $pagination)
->build('genres-list');
}
else
{
$this->template->title($this->_template_title(lang('ebooks:genres_by')))
->set_metadata('description', $this->_template_title(lang('ebooks:genres_by')))
->set_metadata('keywords', $this->_template_title(lang('ebooks:genres_by')))
->set('genres', $genres)
->build('genres-list');
}
}
而且,这是模型:
public function count_genres_by($genre, $params)
{
return $this->db->select('*')
->from('downloads_books_book_info')
->join('keywords_applied', 'keywords_applied.hash = downloads_books_book_info.books_info_genre')
->join('keywords', 'keywords.id = keywords_applied.keyword_id')
->where('keywords.name', str_replace('-', ' ', $genre))
->where($params)
->count_all_results();
}
public function get_genres_by($genre, $params)
{
return $this->db->select('*')
->from('downloads_books_book_info')
->join('keywords_applied', 'keywords_applied.hash = downloads_books_book_info.books_info_genre')
->join('keywords', 'keywords.id = keywords_applied.keyword_id')
->where('keywords.name', str_replace('-', ' ', $genre))
->where($params)
->get()
->result();
}
正如您在代码的第一部分中所看到的,我得到了四次时间(),给出了延迟:
18:49 - 19:03 - 19:41 - 19:41
我有一个大约有5K条目的数据库。如何优化此代码?
答案 0 :(得分:0)
您可以使用2.2.0-beta1并利用搜索系统,该系统会将所有关键字存储为文本,并为您的查询删除一些联接。
否则,您可以使用博客事件构建自己的索引表,博客事件会将关键字存储在博客ID旁边。
主要问题是您在每个返回的项目上运行SQL查询,而一次性计算所有关键字会更快。即使是SQL子查询也会稍快一些。