通过foreach循环传递来自两个相关表的项目

时间:2016-12-23 18:43:18

标签: php mysql codeigniter foreach

我在数据库上有两个表,其中的第二个表用于引用表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>’;
        } ?>

1 个答案:

答案 0 :(得分:1)

您可以在模型getItems()函数中连接表1和表2。像:

模特:

function get_items($id_geral) {
    $query = $this->db->query("SELECT table1.*, id_table_2, item_table_2 FROM table_1 LEFT JOIN table_2 WHERE table_1.id_table_1=table_2.id_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>
    <td>’.$item->id_table_2.’</td>
    <td>’.$item→item_table_2.’</td>
    </tr>’;
    } ?>
相关问题