I'm trying to pull available lectures for a user in my project.
The setup consists of a few tables: Users, Courses and Lectures (+ course_user (pivot table))
When a user is logged in I want to pull the available lectures from the courses the user is enrolled in.
I've done the following, but I'm not sure this is the most efficient way to the available lectures:
// Call from controller
$lectures = Lecture::availableNow($user)->get();
// Local scope in Lecture model
public function scopeAvailableNow($query, $user)
{
return $query->whereHas('course.students', function ($q) use ($user) {
$q->where('id', $user->id);
});
}
The above generates the following SQL query:
select * from "lectures" where exists (select * from "courses" where "lectures"."course_id" = "courses"."id" and exists (select * from "users" inner join "course_user" on "users"."id" = "course_user"."user_id" where "course_user"."course_id" = "courses"."id" and "id" = ? and "course_user"."role" = ?))
Is this an efficient way to get the lectures? Or should I go another way around the models to get to that data?
I raw approach would probably look something like this:
SELECT l.name FROM lectures AS `l`
INNER JOIN courses AS `c` ON c.id = l.course_id
INNER JOIN course_user AS `cu` ON c.id = cu.course_id
WHERE cu.user_id = 3