我正在做一个代码点火器项目,我是代码点火器的新手,但现在在一定程度上理解它。我为 uni 构建了一个简单的应用程序,但在尝试显示哪些项目属于哪些类别时遇到了问题。
我的数据库结构
|------------------| |--------------------| |---------------------------------|
| books | | book_categories | | book_linktable |
|------------------| |--------------------| |---------------------------------|
| book_id | | book_category_id | | book_linktable_book_id |
| book_name | | book_category_name | | book_linktable_book_category_id |
| book_description | |--------------------| |---------------------------------|
| book_grade |
| book_author |
| book_edition |
| book_publisher |
| book_price |
| book_image |
|------------------|
好的,所以在我的模型中使用连接我已经成功地从 book_linktable 中提取了我想要的数据,并且我在我的视图中使用了一个简单的 foreach 循环来显示它。
麻烦的是,假设一本书属于 2 个或更多类别,它在 book_linktable 中看起来像这样:
|------------------------|---------------------------------|
| book_linktable_book_id | book_linktable_book_category_id |
|------------------------|---------------------------------|
| 1 | 1 |
| 1 | 2 |
|------------------------|---------------------------------|
(所以这里第 1 册属于第 1 类和第 2 类)
但是,问题是,当我在视图中执行 foreach 循环时,它将它们显示为两本不同的书,如下所示:
|Name | Grade | Price | Categories |
|---------------------------------------|
|Book1 | Grade 1 | £7.00 | Announcement |
|Book1 | Grade 1 | £7.00 | Event |
我只需要找出如何呼应书籍所在的不同类别,而不是多次显示书籍。像这样的东西:
|Name | Grade | Price | Categories |
|----------------------------------------------|
|Book1 | Grade 1 | £7.00 | Announcement, Event |
这是我的模型函数:
function get_books(){
$this->db->select('books.book_id, books.book_name, books.book_grade, books.book_edition, books.book_price, book_categories.book_category_id, book_categories.book_category_name');
$this->db->from('book_linktable');
$this->db->join('books', 'book_linktable.book_linktable_book_id = books.book_id');
$this->db->join('book_categories', 'book_linktable.book_linktable_book_category_id = book_categories.book_category_id');
$query = $this->db->get();
return $query->result();
} //function get_books()
这是我的控制器功能:
function books($condition = FALSE){
if($condition === TRUE OR $this->admin_model->logged_in() === TRUE)
{
$data = $this->admin_model->display();
$data['query'] = $this->admin_model->get_books();
$data['page_title'] = 'Books';
$this->load->view('admin_section/books/main', $data);
}
else
{
$this->load->view('admin_section/details');
}
} //function books()
这是我在视图中的foreach:
<?php
foreach($query as $row) {
echo "<tr>";
echo "<td>" . $row->book_name . "</td>";
echo "<td>" . $row->book_grade . "</td>";
echo "<td>" . $row->book_edition . "</td>";
echo "<td>" . "£" . $row->book_price . "</td>";
echo "<td>" . $row->book_category_name . "</td>";
echo "<td>" . anchor('books_admin/edit_book/' . $row->book_id, img(array('src'=>'/sys_icons/edit.png','border'=>'0','alt'=>'Edit'))) . " ";
echo "<td>" . anchor('books_admin/delete_book/' . $row->book_id, img(array('src'=>'/sys_icons/delete.png','border'=>'0','alt'=>'Delete', 'class' => 'delete_book'))) . "</td>";
echo "</tr>";
}
?>
任何帮助将非常感激
谢谢,汤姆