How to use "hasManyThrough" with more than three tables in Laravel?

as pointed out in the docs , the current hasManyThrough can be used when you have something likecountry > users > posts

which leads to something like Country::whereName('xx')->posts; that great, but what if I have more than I like

country > cities > users > posts or even

country > cities > towns > users > posts

how would you then implement something like this so that you can write the same as above.

Country::whereName('xx')->posts; or Town::whereName('xx')->posts;

+4
source share
2 answers

Unfortunately, there is no easy solution, so I realized that I found

1- hasMany ,

posts
    id - integer
    country_id - foreign
    // etc...
    title - string

2- hasManyThrough , user post, , ,

countries
    id - integer
    name - string

cities
    id - integer
    country_id - foreign
    name - string

towns
    id - integer
    city_id - foreign
    name - string

users
    id - integer
    town_id - foreign
    name - string

posts
    id - integer
    user_id - foreign
    title - string

-

1- hasMany

2- hasManyThrough .

3- Country::whereName('xx')->posts

// because Country::find($id)->towns, return an array
// so to get all the posts we have to loop over that
// and return a new array with all the country posts
public function posts()
{
    $posts = [];

    foreach ($this->towns as $town) {
        $posts[] = $town->posts;
    }

    return $posts;
}

4, foreign_id, id name, Country::find($id)->posts()

+1

. @ctfo, .

public function posts()
{
    $posts = collect();

    foreach ($this->towns->get() as $town) {
        $post = $town->posts();
        if ( $post->count() ) $posts = $posts->merge( $post );
    }

    return $posts;
}

, , .

+1

Source: https://habr.com/ru/post/1625509/


All Articles