简体   繁体   中英

Access relation in forelse on the same model - laravel

i have a question about accessing relation in laravel model. I have category model which has relation to translation model and category model(same model/itself - one category can be displayed in other categories using pivot table CategoryToCategory):

category model:

    public function childCategories(){
        return $this->hasManyThrough('App\Models\Category',
            'App\Models\CategoryToCategory',
            'id_parent_category', 
            'id',  
            'id',
            'id_category'); 
    }

    public function translation($locale = null)
    {
        if ($locale == null) {
            $locale = \App::getLocale();
        }
        return $this->hasOne('App\Models\CategoryLanguage', 'id_category', 'id')->where('locale', '=', $locale);
    }

Now i take current category + translation + child categories:

$category = Category::with('translation', 'childCategories')->active()->where('id', $id)->first();

And display all childs names:

@forelse($category->childCategories as $category)
   {{ $category->translation->name }}
@endforelse

I works but each child category makes another query to get translation(it's not loaded for elements in forelse). So how to load relation "translation" in category model which is foreaching loaded relation?

I could query model CategoryToCategory to get all child categories + load translation for that model and result be the same:

$categories = CategoryToCategory::with('translation')->where('id_parent_category', $id)->get();

And there will be one query for translations. Still i'm curious about using first solution instead query categoryToCategory.

Any ideas?

Have a nice day!

To eager load a distant relationship you can use the dot notation like so:

$category = Category::with('translation', 'childCategories.translations')
    ->active()
    ->where('id', $id)
    ->first();

This is known as "nested eager loading" and is referenced in the docs here: https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM