【发布时间】:2010-09-29 16:03:08
【问题描述】:
我正在 CodeIgniter 之上编写一个应用程序,以更好地组织我的电子书收藏。我快完成了,但我意识到我的“浏览”页面正在运行太多查询——每本书两个——以获取他们的信息。显然一点也不理想,特别是因为我有大约 1000 本书要放入这个系统。
我目前有一个模型函数可以获取所有书籍(最终将被修改为采用参数 - 这是下一步),另一个模型函数可以获取每本返回书籍的元信息。第二个函数是对每本书进行两次查询的函数——一个获取图书表中的信息,另一个获取与图书关联的标签。下面是两个模型函数:
获取书籍列表:
function get_books() {
$this->db->select('isbn')->order_by('title');
$query = $this->db->get('books');
$result = $query->result();
return $result;
}
获取图书元信息:
function get_book_info($isbn) {
// Grab the book from Amazon
$amazon = $this->amazon->get_amazon_item($isbn);
// Get the book info
$this->db->select('title, publisher, date, thumb, filename, pages');
$query = $this->db->get_where('books', array('isbn' => $isbn));
$bookResult = $query->row();
// Get the book's tags
$this->db->select('tag');
$this->db->from('tags AS t');
$this->db->join('books_tags AS bt', 'bt.tag_id = t.id', 'left');
$this->db->where('bt.book_id', $isbn);
$this->db->order_by('t.tag');
$tagQuery = $this->db->get();
foreach ($tagQuery->result() as $row) {
$tagResult[] = $row->tag;
}
$tagResult = implode(', ', $tagResult);
// Send data
$data = array(
'isbn' => $isbn,
'thumb' => $bookResult->thumb,
'title' => strip_slashes($bookResult->title),
'file' => $bookResult->filename,
'publisher' => strip_slashes($bookResult->publisher),
'date' => date('F j, Y', strtotime($bookResult->date)),
'pages' => $bookResult->pages,
'tags' => $tagResult,
'rating' => $amazon->Items->Item->CustomerReviews->AverageRating,
'raters' => $amazon->Items->Item->CustomerReviews->TotalReviews
);
return $data;
}
我确信有一种方法可以编写一两个查询,将所有记录收集到我可以过滤的对象中,而不必为每个查询编写两个查询,但我什至不知道从哪里开始试着写那个。欢迎任何建议。
非常感谢, 马库斯
【问题讨论】:
标签: php mysql activerecord codeigniter