lundi 7 août 2017

How to count number of grandchildren of a model in Laravel 5?

Let say I have a database like the following:

Teacher Table
----------------
teacher id (integer, primary key)
... some other teach info ...

Lesson Table
----------------
lesson id (integer, primary key)
teacher id (integer, foreign key to teach table)
... some other lesson info ...

Student Table
----------------
student id (integer, primary key)
... some other student info ...

Student Lesson Pair Table
----------------
pair id (integer, primary key)
student id (integer, foreign key to Student table)
lesson id (integer, foreign key to Lesson table)

One lesson only got one teacher, while a teacher can teach multiple lessons. Student can take multiple lessons and a lesson has multiple students.

To retrieve my information, I have written the model in a way such that the following will work:

$teachers = Teacher::with('lesson', 'lesson.studentLessonPair', 'lesson.studentLessonPair.student')->get();

Is there a way I can retrieve the number of (or if possible, a list of) unique student taught by a teacher without making another database call?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire