Scout APM helps PHP developers pinpoint N+1 queries, memory leaks & more so you can troubleshoot fast & get back to coding faster. Start your free 14-day trial today.

Laravel's HasManyThrough cheatsheet

- The current model <hljs red>Country</hljs> has a relation to <hljs yellow>Post</hljs> via <hljs blue>User</hljs>
- The <hljs blue>intermediate model</hljs> is linked to the <hljs red>current model</hljs> via <hljs blue>users.country_id</hljs>
- The <hljs yellow>target model</hljs> is linked to the <hljs blue>intermediate model</hljs> via <hljs yellow>posts.user_id</hljs>
- <hljs blue>users.country_id</hljs> maps to <hljs red>countries.id</hljs>
- <hljs yellow>posts.user_id</hljs> maps to <hljs blue>users.id</hljs>
<hljs red>countries</hljs>
    <hljs red>id</hljs> - integer
    name - string

<hljs blue>users</hljs>
    <hljs blue>id</hljs> - integer
    <hljs blue>country_id</hljs> - integer
    name - string

<hljs yellow>posts</hljs>
    id - integer
    <hljs yellow>user_id</hljs> - integer
    title - string
class Country extends Model
{
    public function posts()
    {
        return $this->hasManyThrough(
            'App\Post',
            'App\User',
            'country_id', // Foreign key on users table...
            'user_id', // Foreign key on posts table...
            'id', // Local key on countries table...
            'id' // Local key on users table...
        );
    }
}