我有两张桌子,即
tbl_tools
和tbl_tool_use
。
tbl_tool_use
桌子看起来像这样
id user_id type tool_id quantity start_date end_date
30 27 engineer 5 2 2016-12-22
31 gdf team 8 2 2016-12-22
32 26 engineer 7 2 2016-12-22
33 26 engineer 7 2 2016-12-23
34 hamsu team 6 2 2016-12-22
35 27 engineer 7,5 2,2 2016-12-22
tbl_tools
桌子看起来像这样
id name quantity available type
5 cutting player 5 5 engineer
6 reflectors 2 2 team
7 spanner 8 8 engineer
8 tester 4 4 team
我希望我的结果是这样的:
id user_id type tool_id quantity start_date end_date
30 27 engineer cutting player 2 2016-12-22
31 gdf team tester 2 2016-12-22
32 26 engineer spanner 2 2016-12-22
33 26 engineer spanner 2 2016-12-23
34 hamsu team reflectors 2 2016-12-22
35 27 engineer cutting player,spanner 2,2 2016-12-22
但是我变成这样了
id user_id type tool_id quantity start_date end_date
30 27 engineer cutting player 2 2016-12-22
31 gdf team tester 2 2016-12-22
32 26 engineer spanner 2 2016-12-22
33 26 engineer spanner 2 2016-12-23
34 hamsu team reflectors 2 2016-12-22
35 27 engineer cutting player 2,2 2016-12-22
如果我选择了更多
tool_id
,那么也只显示一个值。
这是我使用的代码,我的视图看起来像这样,我只显示了代码中受影响的部分
<tbody>
<?php $n=1;
foreach($all_assign_tool_info as $row) {
$t=explode(',',$row->tool_id);
foreach($tools as $res) {
foreach($t as $res1) {
if($res1==$res->id) {
$tool=$res->name;
//var_dump($tool);
}
}
}
}
?>
<tr>
<td><?= $tool ?></td>
</tr>
<?php
}?>
</tbody>
这是我的控制器
public function assign_tool($id = NULL)
{
$data['all_assign_tool_info'] = $this->Tool_model->get_permission('tbl_tool_use');
$data['tools']=$this->Tool_model->view_tools(null,null);
$data['subview'] = $this->load->view('admin/tool/assign_tool',$data, TRUE);
$this->load->view('admin/_layout_main', $data); //page load
}
我的模型是这样的
public function view_tools($limit,$offset)
{
$this->db->order_by('id','desc');
$query=$this->db->get('tbl_tools',$limit,$offset);
return $query->result();
}
这是新包含的代码 我的
tbl_tool_use
桌子看起来像这样
id user_id type tool_id quantity start_date end_date
136 27 engineer 11,5,7 3,5,2 2016-12-22
这意味着
tool_id
11
是 3
,5
是 5
和 7
分别是 2
但结果是这样的5
是3
,7
是5
和11
是2
我会放弃 PHP 中的迭代,而更多地专注于编写正确的 SQL 语法来获取结果。查看
FIND_IN_SET
和 JOINS
来完成这项工作。本质上,您想要的是以逗号分隔值连接两个表。我会用这种方式重写你的 Codeigniter 模型:
public function view_tools($limit,$offset)
{
$this->db->select('tu.*, GROUP_CONCAT(t.name ORDER BY t.id) as tool_id', FALSE);
$this->db->from('tbl_tools t');
$this->db->join('tbl_tools_use tu', 'FIND_IN_SET(t.id, tu.tool_id)', 'inner', FALSE);
$this->db->group_by('tu.id');
$this->db->order_by('tu.id','desc');
$this->db->limit($limit);
$this->db->offset($offset);
$query = $this->db->get();
return $query->result();
}