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

363
August 07, 2017, at 4:23 PM

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 by only changing the code in model, without making another database call?

Rent Charter Buses Company
READ ALSO
How to get high-res thumbnails out of low-res SVGs in Mediawiki?

How to get high-res thumbnails out of low-res SVGs in Mediawiki?

I don't exactly know how to word this question properly, so I'll make an attempt:

305
Filter specific column in array in php

Filter specific column in array in php

I am trying to filter a specific column in an array in php using the code below:

264
Howto replace hyphen with shy inside paragraph with preg_replace

Howto replace hyphen with shy inside paragraph with preg_replace

How to search and replace hyphens within paragraphs to &shy?

205
application/json all requests going to 403

application/json all requests going to 403

Through postman, I am posting data to specific URL like sitecom/read_request

235