0

I've a following attendance table:

id | grade_id | subject_id |    date    |        students
 1 |     2    |      6     | 2020-05-05 | [3,6,8,11,17,21,20,19] 

I want to fetch all rows with name of all students from array of Ids. What I've tried is:

$result[] = Attendance::where('date', '=', $day)
                ->with('grades', 'subjects')
                ->join('students', function($join) {
                      $join->on('students.id', '=', 'attendances.id')
                           ->where('students.id', '=', 'attendances.students');
                      })->get();

But couldn't get result. Please help me!

Dipen Chand
  • 95
  • 11
  • 1
    You should've have been used [Many To Many relationship](https://laravel.com/docs/7.x/eloquent-relationships#many-to-many). – Mihai Matei May 06 '20 at 09:32
  • 3
    It would be easier to do normalization on `students` column - instead of keeping them as an array on a single column, you may use a pivot table to match student ids with the related attendance id. Please check this link, it explains it very well https://stackoverflow.com/a/17371788/2188922 – Ersoy May 06 '20 at 09:33
  • 1
    I agree with @Ersoy – justkidding96 May 06 '20 at 10:04
  • Thank you Everyone! I achieved the result using @Ersoy 's way. – Dipen Chand May 06 '20 at 11:44

1 Answers1

1

It is not a proper table structure.Will be better if you make another table like

id | attendance_id | student_id
1  | 1             | 3
1  | 1             | 6

And make its relation in model with attendance and student table.This way table will be normalized and will be easy to handle relationship.

Rana Nadeem
  • 1,115
  • 1
  • 9
  • 17