A HasManyThrough relationship allows a model to access related records through an intermediate model, without directly linking the two tables.
Real-World Examples
- Country → Users → Posts
- Course → Modules → Lessons
- Company → Departments → Employees
- Category → Products → Reviews
1.When to Use HasManyThrough
Use hasManyThrough when:
- You have two one-to-many relationships
- You want to skip the middle model while querying
- You want clean & optimized queries
❌ Do NOT use it for many-to-many relationships.
2. Example Scenario (Country → Users → Posts)
Relationship Chain
Goal:
👉 Get all posts of a country, without manually looping users.
3.Database Structure
countries table
users table
posts table
4.Model Creation
5.Define Normal Relationships First
Country.php
User.php
6.Define HasManyThrough Relationship
Country.php
✔ That’s it! Laravel figures out the keys automatically.
7.How Laravel Resolves the Keys
Laravel assumes:
| Key Type | Column |
|---|---|
| Foreign key on users | country_id |
| Foreign key on posts | user_id |
| Local key on countries | id |
| Local key on users | id |
8.Fetch Data Using HasManyThrough
Loop Example
9.SQL Behind the Scene (Simplified)
✔ Single optimized query
10.Custom Foreign & Local Keys
If your column names are different:
Method Parameters Order
11.Add Conditions
12.Ordering Results
13.Count Related Records
Optimized:
14.Eager Loading HasManyThrough
15.Real LMS Example (Course → Modules → Lessons)
Database
Course.php
Usage
✔ No need to loop modules manually
