无法从2表创建所需的数组

时间:2018-03-29 09:50:17

标签: php mysql codeigniter

我有3个表,如下所示

学生

id  student_name
1      S1
2      S2
3      S3
4      S4

教师

id    teacher_name
1       T1
2       T2
3       T3

id   student_id   teacher_id
1       1             1
2       2             1

我希望结果数组像这样

Array
(
    [0] => stdClass Object
        (
            [student_id] => 1
            [teacher_id] => 1
        )

    [1] => stdClass Object
        (
            [student_id] => 2
            [teacher_id] => 1
        )

    [2] => stdClass Object
        (
            [student_id] => 3
            [teacher_id] =>
        )
    [3] => stdClass Object
        (
            [student_id] => 4
            [teacher_id] =>
        )
)

我正在使用的查询是

$query = $this->db->select('*')
  ->from('class')
  ->join('student', 'student.id = class.student_id', 'left')
  ->join('teacher', 'teacher.id = class.teacher_id', 'left')
  ->get();

我进入数组的结果是

Array
(
    [0] => stdClass Object
        (
            [student_id] => 1
            [teacher_id] => 1
        )

    [1] => stdClass Object
        (
            [student_id] => 2
            [teacher_id] => 1
        )
)

任何人都可以告诉我需要做些什么改变才能获得理想的结果

1 个答案:

答案 0 :(得分:1)

你应该在课堂表上加入学生和教师表。但我没有测试过这个。

$query = $this->db->select('student.id, teacher.id')
  ->from('student')
  ->join('class', 'class.student_id = student.id', 'left')
  ->join('teacher', 'teacher.id = class.teacher_id', 'left')
  ->get();