我尝试在codeigniter模型中运行查询。它工作但是当我回显模型函数查询时如下所示。
SELECT * FROM `table1` WHERE `id` = '17'
SELECT * FROM `table1` WHERE `id` = '20'
SELECT * FROM `table1` WHERE `id` = '21'
SELECT * FROM `table1` WHERE `id` = '22'
SELECT * FROM `table1` WHERE `id` = '23'

我的模型功能如下:
function get_quick_navi_menu($q_code)
{
$this->db->select("*");
$this->db->where('q_id',$q_code);
$this->db->from("table0");
$q = $this->db->get();
//echo $this->db->last_query();
$final = array();
if ($q->num_rows() > 0)
{
foreach ($q->result() as $row) {
$this->db->select("*");
$this->db->from("table1");
$this->db->where("id",$row->id);
$q = $this->db->get();
echo $this->db->last_query();
if ($q->num_rows() > 0) {
$row->children = $q->result();
}
array_push($final, $row);
}
}

我想运行如下的查询
SELECT * FROM `table1` WHERE `id` = '17,18,19..'

Table0
id q_id value1
1 2 4
2 2 5
3 2 6
Table1
t1_id id value1 value2
1 1 2 2
2 2 5 6
3 3 8 12

<ul class="dropdown-menu" aria-labelledby="dropdownMenu1" style="margin-left: 1px; opacity: .9;">
<?php foreach ($menus as $menu) { ?>
<li class="dropdown-submenu"><a href="#" class="pan-btn" data-look="<?php echo $menu->sceneid;?>"><?php echo $menu->title;?></a>
<ul class="dropdown-menu"> <?php
if (isset($menu->children)) {
foreach ($menu->children as $child) {?>
<li><a href="#" class="pan-btn" data-look="<?php echo $child->menu_scene;?>"><?php echo $child->menu_item;?></a></li> <?php
}
}
?></ul></li><?php } ?>
</ul>
&#13;
$menus = $this->Home_model->get_quick_navi_menu($q_code);
$data = array('menus' => $menus);
&#13;
必需的输出
根据table0中的id从table1中选择value1和value2。 如何解决这个请帮助。
答案 0 :(得分:1)
在控制器中使用此功能
public function getTableData()
{
$this->db->select('GROUP_CONCAT(id) as id');
$tbl0 = $this->db->get('table0')->row_array();
if($tbl0) {
$ids = explode(',', $tbl0['id']);
$this->db->where_in('id', $ids);
$tbl1 = $this->db->get('table1')->result_array();
echo "<pre>"; print_r($tbl1);
}
}
答案 1 :(得分:0)
希望这会对您有所帮助;
在此处获取数组名称中的所有ids
并在循环外使用where_in
public function get_quick_navi_menu($q_code)
{
$this->db->select("*");
$this->db->where('q_id',$q_code);
$this->db->from("table0");
$q = $this->db->get();
$final = array();
if ($q->num_rows() > 0)
{
foreach ($q->result() as $key => $row)
{
$ids[$key] = $row->id;
$data[$key] = $row;
}
$this->db->select("*");
$this->db->from("table1");
$this->db->where_in("id",$ids);
$q = $this->db->get();
//echo $this->db->last_query();
if ($q->num_rows() > 0)
{
if ( ! empty($data))
{
foreach ($data as $key => $item)
{
$item->children = $q->result();
$final[] = $item;
}
}
}
}
return $final;
/*print_r($final);*/
}
在您的控制器类中:
确保您已在控制器或autoload.php中加载模型和数据库
$q_code = 'q_code_value';
$data['menus'] =$this->Home_model->get_quick_navi_menu($q_code);
/* pass the $data in the view like this*/
$this->load->view('your_view_file_path',$data);
在您看来:
<div><?php print_r($records);?></div>
更多信息:https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data