【问题标题】:Passing items from two related tables through foreach loop通过 foreach 循环从两个相关表中传递项目
【发布时间】: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


【解决方案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>’;
    } ?>

【讨论】:

  • 也许我已经简化了太多,因为我已经链接了模型上的其他表。如果在我的模型上我会有function get_descritivo_analises($id_geral) { $query = $this-&gt;db-&gt;query("SELECT table_1.*, table_3.*, table_4.*, (SELECT COUNT(id_table_2) FROM table_2 WHERE table_2.id_table_1=table_1.id_table_1) AS contagem FROM table_1, table_3, table_4 WHERE table_1.id_table_4=table_4.id_table_4 AND table_1.id_table_Xl='" . $id_geral . "' AND table_1.id_table_3=table_3.id_table_3"); return $query-&gt;result(); },我会怎么做
  • 您提出的问题已在此处得到解答。如果您还有其他问题,请发布一个新问题,请避免使用 dhit table1、table2、x、y、废话并发布真实表格
  • @Baya 你得到答案了吗?
猜你喜欢
  • 1970-01-01
  • 2016-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
相关资源
最近更新 更多