phplaraveleloquenttable-relationships

Laravel - Retrieve collections through two pivot tables


I'm currently struggling with the following issue in Laravel 5.6, let's say I have the following database tables:

  1. Websites (e.g. id|name)
  2. Website_providers (e.g. id|website_id|provider_id)
  3. Provider_posts (e.g. id|provider_id|post_id|post_name)
  4. Posts (e.g. id|name)

I'm looking for a nice way to retrieve the posts based on a website ID. A website can have multiple providers assigned (through website_providers) and providers can have multiple posts assigned to them (also can they provide a custom post_name which should overrule the standard posts.name).

What is the best way to achieve this in Laravel? I've yet tried doing it through relations, but can't get it too work smoothly. I also tried loading the posts using a pretty long join query, but it just doesn't feel right, there's got to be a more simple and prettier way.

Thanks in advance!


Solution

  • There is no native relationship for this case.

    I created a HasManyThrough relationship with support for BelongsToMany: Repository on GitHub

    After the installation you can use it like this:

    class Website extends Model {
        use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    
        public function posts() {
            return $this->hasManyDeep(
                Post::class,
                ['website_providers', Provider::class, 'provider_posts']
            )->withPivot('provider_posts', ['post_name']);
        }
    }