HasManyThrough with one-to-many relationship

You can’t do it with builtin methods, hasManyThrough won’t work with many-to-many relation menus-pages.

However you can try a workaround like this:

public function getTranslationsAttribute()
{
    if ( ! array_key_exists('translations', $this->relations)) $this->loadTranslations();

    return $this->getRelation('translations');
}

protected function loadTranslations()
{
    $translations = Translation::join('menu_page', 'translations.page_id', '=', 'menu_page.page_id')
        ->where('menu_page.menu_id', $this->getKey())
        ->distinct()
        ->get(['translations.*','menu_id']);

    $hasMany = new Illuminate\Database\Eloquent\Relations\HasMany(Translation::query(), $this, 'menu_id', 'id');

    $hasMany->matchMany(array($this), $translations, 'translations');

    return $this;
}

Now you can do this:

$menu = Menu::find($id);
$menu->translations; // Eloquent Collection of Translation models

So basically just like you would use any relation. The only trouble is that you can’t eager load it.

Leave a Comment