【发布时间】:2017-05-09 10:52:50
【问题描述】:
我在数据库中有两个表,其中第二个表的项目引用表 1。 我通过 foreach 循环将 table_1 中的项目传递到视图中,并且我想在每个项目中包含 table_2 中相关项目的列表,只要它们存在。
我该怎么做:
id_table_1 | item_table_1
---------- | ------------
1 | item 1
2 | item 2
3 | item 3
id_table_2 | item_table_2 | id_table_1
-----------|--------------|-----------
1 | pic 1 | 1
2 | pic 2 | 1
3 | pic 3 | 1
4 | pic 4 | 2
5 | pic 5 | 3
控制器:
function view()
{
$data['main_content'] = 'things';
$this->load->model('main_model');
$data['items'] = $this->main_model->get_items();
$this->load->view('includes/template', $data); }
模型:
function get_items($id_geral) {
$query = $this->db->query("SELECT * FROM table_1");
return $query->result();
}
观点:
<table>
<thead>
<tr>
<th>id_table_1</th>
<th>item_table_1</th>
</tr>
</thead>
<tbody>
<?php foreach ($items as $items) {
echo ‘
<tr>
<td>’.$item->id_table_1.’</td>
<td>’.$item→item_table_1.’</td>
</tr>’;
} ?>
【问题讨论】:
-
你尝试了什么?
-
我不知道我是否想过要做类似的事情:
SELECT table_1.*, table_2.* FROM table_1, table_2 WHERE table_2.id_table_1=table_1.id_table_1但是我会从 table_1 中获得与 table_2 相关的项目数一样多的相同项目,而且我' d 想一次回显 table_1 中的每个项目...
标签: php mysql codeigniter foreach