[英]check if all elements of an array exists in a table in laravel
我有courses
和student_courses
表。 如果學生完成一門課程,我將在student_courses
表中插入一個帶有student_id
和course_id
。 現在,我有一個場景,如果學生完成了一定數量的課程,則需要從student_courses
表中獲取所有student_ids
。 我從另一個查詢中獲取course_ids
作為數組。 有沒有辦法在laravel中有效地進行此查詢,因為student_courses
表中已經有100k +數據了?
不知道使用查詢,但是可以使用array_intersect()函數來實現。
// 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');
現在您可以使用array_intersect()
$result = array_intersect($completedCourses, $checkCourses);
if(!empty($result)) {
// your code...
}
以下查詢將提供完成課程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");
其中count 3是您要檢查的總課程的大小,在上面的查詢中,我們正在檢查課程ID 1,3,4,因此HAVING COUNT(*)為3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.