arthur.flachs
arthur.flachs

Reputation: 136

Laravel Eloquent - belongs to many through

I have sites, pages, elements and element_creators tables, like this :

   sites
     id
     ...
   pages
     id
     site_id
     ...
   elements
     id
     page_id
     ...
   element_creators
     id
     element_id
     ...

I'm able to retrieve element creators linked to a page

    $this->belongsToMany('ElementCreator', 'elements', 'page_id', 'element_creator_id');

Is there a simple way to retrieve all element creators for a specific site (through its pages) ?

Thank you !

Upvotes: 2

Views: 5722

Answers (2)

The Alpha
The Alpha

Reputation: 146249

You may try this:

$site = Site::with('pages.elementCreators')->find(1); // 1 is id for example

Then you may access all the elementCreators using this:

$elementCreators = $site->pages->fetch('elementCreators');

Upvotes: 1

arthur.flachs
arthur.flachs

Reputation: 136

For now, I'm using this as a temporary solution, I hope to find something better :

    public function elementCreators()
    {
        $elementCreators = array();
            foreach ($this->pages as $page) {
                foreach ($page->elementCreators as $elementCreator) {
                    $elementCreators[$elementCreator->id] = $elementCreator;
                }
            }
        return \Illuminate\Database\Eloquent\Collection::make($elementCreators);
    }

Upvotes: 0

Related Questions