我的桌子是这样的
我想获取所有部门,如果
location_id
是3
,这意味着如果使用位置ID3
,我需要获取cardiology
和hair
的部门名称,这样我就可以像这样完成我的代码
我的
controller
看起来像这样
public function get_location_departments()
{
$d = $_POST['location'];
$data['departments'] = $this->Hospital_model->get_location_departments($d);
$this->load->view('frontend/ajax_get_departments',$data);
}
我的
model
看起来像这样
public function get_location_departments($d)
{
$this->db->where_in('location_id',$d);
$query=$this->db->get('department')->result();
return $query;
}
请帮我解决我的问题
希望这对您有帮助:
您必须先查询才能获取
department
并使用 explode
将 location_id 放入数组中
你的模型
get_location_departments
方法应该是这样的:
public function get_location_departments($d)
{
if (! empty($d))
{
$query = $this->db->get('department');
if ($query->num_rows() > 0 )
{
foreach ($query->result() as $location)
{
$location_ids = explode(',',$location->location_id);
if (in_array($d, $location_ids))
{
$data[] = $location;
}
}
}
return $data;
//print_r($data);
}
}
恕我直言,正确答案是
public function get_location_departments($d)
{
$query = $this->db
->where('FIND_IN_SET('.$this->db->escape($d).', location_id)', NULL, false)
->get('department')
->result();
return $query;
}
为此目的有一个名为
的函数。您可以在 mysql 文档中找到它,位于 https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_find-in-setFIND_IN_SET