I have courses and student_courses table. If a student completed a course I'm inserting a row in student_courses table with student_id and course_id. Now I have a scenario where I need to get all student_ids from student_courses table if a student completed certain numbers of courses. I am getting course_ids from another query as an array. Is there any way to make this query efficiently in laravel, because there is already 100k+ data in student_courses table?
-
What have you tried? Also please post your models with the relationshipsAhmed Nour Jamal El-Din– Ahmed Nour Jamal El-Din2019-02-07 04:46:43 +00:00Commented Feb 7, 2019 at 4:46
-
This broad requirements dump contains no code and no sample data.mickmackusa– mickmackusa ♦2024-03-09 22:30:06 +00:00Commented Mar 9, 2024 at 22:30
Add a comment
|
1 Answer
Don't know using query, but you can do that using array_intersect() function.
// get all courses id you want to check into one array
$checkCourses = [1,2,...];
// get all courses completed by student
$completedCourses = StudentCourse::where('student_id', $studentId)->pluck('course_id');
now you can use array_intersect()
$result = array_intersect($completedCourses, $checkCourses);
if(!empty($result)) {
// your code...
}
following query will gives the student who completed course id (1,3,4)
DB::query("SELECT student_id FROM student_courses WHERE course_id IN (1,3,4) GROUP BY student_id HAVING COUNT(*) = 3");
where count 3 is size of total course you want to check, in above query we are checking with course id 1,3,4 so HAVING COUNT(*) is 3
3 Comments
Alauddin Ahmed
Thanks for your time, But how would i get student ids, when my requirement is to get those.
Ravi Gaudani
@AlauddinAhmed I added query, please check and update as per your requirenment.
Alauddin Ahmed
I will check the result and let you know,. Thanks again.