Denis Rozimovschii
Denis Rozimovschii

Reputation: 448

Laravel 5.4 hasManyThrough with a second local key

The current state of the database

User
----
id 
name
UserCourse
----
id
user_id
course_id
Homework
----
id
course_id
name

Details: Users can subscribe to multiple courses and their subscription is held in the UserCourse table. Courses can have multiple homeworks.

Question: somebody wants to access all the homeworks from all the courses an user has subscribed to.

So one user hasMany subscriptions to courses and each course hasMany homeworks. So the obvious solution is to use this code from the User Model.

$this->hasManyThough('App\Homework', 'App\UserSubscribedToCourse', 'user_id', 'course_id'),

but this generates the following query

select homeworks.*, user_course.user_id from homeworks inner join user_course on user_course.id = homeworks.course_id where user_course.user_id = 51

As you can see, it falsely thinks that it should match user_course.id with the foreign key homeworks.course_id, but the correct localKey should be user_course.course_id.

As far as I can see from the source code, only localKey for the User table can be specified.

This has been fixed in laravel 5.5 with this pull request: https://github.com/laravel/framework/pull/19114

Is there a way to perform this in laravel 5.4?

Upvotes: 0

Views: 242

Answers (1)

linktoahref
linktoahref

Reputation: 7972

Access all the homeworks from all the courses an user has subscribed to.

Get all the courses the User has subscribed to

$user_id = Auth::user()->id;
$courses = UserCourse::where('user_id', $user_id)->pluck('course_id');

Get all the homeworks from the courses

$homework = Homework::whereIn('course_id', $courses)->get();

Upvotes: 1

Related Questions