HasManyThrough with one-to-many relationship

前端 未结 1 1146
情书的邮戳
情书的邮戳 2020-11-29 07:38

I am working on small scale CMS for a project with tables like so:

- pages
    - id
    …
- translations
    - page_id
    …
- menus
    - id
    …
- menu_pa         


        
相关标签:
1条回答
  • 2020-11-29 08:42

    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.

    0 讨论(0)
提交回复
热议问题