Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'hasManyThrough' with more than 3 tables in Laravel?

as stated in the docs the current hasManyThrough can be used when u have something like country > users > posts

which result in something like Country::whereName('xx')->posts; which is great but what if i have more than that like

country > cities > users > posts or even

country > cities > towns > users > posts

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

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

like image 250
ctf0 Avatar asked Jan 22 '16 13:01

ctf0


2 Answers

I created a HasManyThrough relationship with unlimited levels: Repository on GitHub

After the installation, you can use it like this:

class Country extends Model {
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function posts() {
        return $this->hasManyDeep(Post::class, [City::class, Town::class, User::class]);
    }
}
like image 110
Jonas Staudenmeir Avatar answered Jan 04 '23 11:01

Jonas Staudenmeir


Here's what I've done. I did some modification to @ctfo's answer, so it will return as collection.

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

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

    return $posts;
}

I hope this can help anyone who came through.

like image 36
LrdArc Avatar answered Jan 04 '23 11:01

LrdArc