我有两张表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
s,那么也只显示一个值。
这是我使用的代码,我的视图看起来像这样,我只在代码中显示了受影响的部分
<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
得到的结果如下
Valid XHTML http://spdc.in/demo/spectra/spectra_tool.PNG 的
答案 0 :(得分: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();
}