我有2个表,如下所示
teacher_student
id teacher_id student_id
1 2 1
2 2 2
3 2 3
4 3 2
5 3 4
学生
id name age
1 n1 12
2 n2 13
3 n3 14
4 n4 15
我希望向所有学生展示每位老师的详细信息
为此,我有以下代码 -
模型
public function get_assigned_student($teacherid)
{
$this->db->where('teacherid',$teacherid);
$query = $this->db->get('teacher_student');
$data = $query->result();
foreach ($data as $main_data)
{
$student_id = $main_data->student_id;
$this->db->where('id',$student_id);
$main_query = $this->db->get('student');
$main = $main_query->result();
//echo "<pre>";
//print_r($main);
//echo "</pre>";
return $main;
}
}
控制器
public function request($teacherid)
{
print_r($this->student_model->get_assigned_student($teacherid));
}
问题是,当我尝试在控制器下打印结果(用于测试目的)时,我只得到一个值,因为我应该得到一个完整的数组。谁能告诉我哪里出错了?
答案 0 :(得分:0)
您似乎必须按照以下代码返回数组中的值:
foreach ($data as $main_data)
{
$student_id = $main_data->student_id;
$this->db->where('id',$student_id);
$main_query = $this->db->get('student');
$main[] = $main_query->result_array();
}
return $main;
使用 result_array()代替 result();
试试这可能会对你有所帮助。
感谢。
答案 1 :(得分:0)
试试这样......
控制器
public function request($teacherid)
{
$this->load->model('student_model');
$records=$this->student_model->get_assigned_student($teacherid);
print_r($records);
}
模型
public function get_assigned_student($teacherid)
{
$this->db->where('teacher_id',$teacherid);
$query = $this->db->get('teacher_student');
$data = $query->result_array();
$std = array();
foreach ($data as $main_data)
{
$student_id = $main_data->student_id;
$this->db->where('id',$student_id);
$main_query = $this->db->get('student');
$main_data = $main_query->result_array();
//echo "<pre>";
//print_r($main_data);
//echo "</pre>";
$std = array_merge($std,$main_data);
}
return $std;
}