4

Laravel's HasManyThrough cheatsheet

 2 years ago
source link: https://stitcher.io/blog/laravel-has-many-through
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Laravel's HasManyThrough cheatsheet

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.

« back — written by Brent on November 08, 2019

Laravel's HasManyThrough cheatsheet

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

users
    id - integer
    country_id - integer
    name - string

posts
    id - integer
    user_id - 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...
        );
    }
}

Footnotes

Building custom relation classes in Laravel

Next up:  Laravel beyond CRUD: the next chapter

Follow me: TwitterRSSNewsletterPatreonGitHub

© 2021 stitcher.io — Cookies & Privacy


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK