【发布时间】:2019-09-02 03:51:03
【问题描述】:
我需要在 CodeIgniter 中使用foreach 方法获取两个关系表。这只是我在我的问题中提供的一个示例代码,我肯定会在我未来的项目中需要它,而且我完全不知道要执行什么样的查询。
这是买家表:
+----+------+
| id | name |
+----+------+
| 1 | John |
| 2 | Jane |
+----+------+
这是商品表:
+----+----------+------------+
| id | buyer_id | goods_name |
+----+----------+------------+
| 1 | 1 | Apple |
| 2 | 1 | Grape |
| 3 | 1 | Banana |
| 4 | 2 | Pear |
| 5 | 2 | Mango |
+----+----------+------------+
在我的模型文件mtest中:
public function buyer_list()
{
$this->db->select('*');
$this->db->from('buyer');
$query = $this->db->get();
return $query->result();
}
public function order_list()
{
$this->db->select('*');
$this->db->from('goods');
$this->db->join('buyer', 'buyer.id = goods.buyer_id', 'inner');
$query = $this->db->get();
return $query->result();
}
在我的控制器中:
public function index()
{
$this->load->model('mtest');
$data['buyer'] = $this->mtest->buyer_list();
$data['order'] = $this->mtest->order_list();
$this->load->view('example', $data);
}
在我的视图文件中示例:
<div id="container">
<?php foreach ($buyer as $buyer_list): ?>
<strong><?php echo $buyer_list->name ?></strong>:
<ul>
<?php foreach ($order as $order_list): ?>
<li><?php echo $order_list->goods_name ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
</div>
上面的代码只显示了整行 goods 表。我想要这样的结果:
+------+------------+
| John | : • Apple |
| | • Grape |
+ + • Banana +
| | |
+ Jane + : • Pear +
| | • Mango |
+------+------------+
对不起,我的英语不好。有什么想法吗?
【问题讨论】:
-
在您的
foreach循环中,您正在覆盖变量。 -
您已经在
order中拥有buyers,因为您加入了表格,因此无需调用buyer_list()函数。
标签: php mysql codeigniter foreach fetch