select 查询中的 codeigniter 4 select

codeigniter 4 select in select query

我是 CodeIgniter 4 的新手,我想用 CodeIgniter 编写这个查询, 怎么做?

SELECT student_id FROM student_rel_class WHERE class_id IN (
    SELECT class_id FROM courses WHERE courses.id IN (
    SELECT course_id FROM homework WHERE homework.id = 41
    ));

谢谢。

这是我的 CodeIgniter 代码

$notifications = $stu_rel_class
         ->select('student_rel_class.student_id')
         ->whereIn('student_rel_class.class_id',function (BaseBuilder $builder) use ($data) {
   return $builder->select('courses.class_id')
      ->from('courses')
      ->whereIn('courses.id',function (BaseBuilder $builder) use ($data) {
         return $builder->select('homework.course_id')
             ->from('homework')
             ->where('homework.id',$data['id'])
             ->first();
         });
});

我也可以像这样连接表

$notifications = $stu_rel_class
        ->select('student_rel_class.student_id')
        ->join('courses','student_rel_class.class_id = courses.class_id','inner')
        ->join('homework','homework.course_id = courses.id')
        ->where('homework.id',$data['id'])
        ->findAll();

但我不想使用连接。 谁能帮帮我?

这可以在 Codeigniter Documentation

中找到
$db = \Config\Database::connect();

$query = $db->query("SELECT student_id FROM student_rel_class WHERE class_id IN (SELECT class_id FROM courses WHERE courses.id IN (SELECT course_id FROM homework WHERE homework.id = 41")));

$results = $query->getResultArray();

希望这有助于解决问题。