A
A
Analka2020-05-30 00:22:14
Laravel
Analka, 2020-05-30 00:22:14

How to display the daughters of the category and the description of the category?

there is a Category model

protected $table = 'categories';

    protected $fillable = [
        'image','parent','sort_order','published'
    ];

    public function categories()
    {
        return $this->hasMany(Category::class, 'parent');
    }

    public function childrens()
    {
        return $this->hasMany(Category::class, 'parent')->with('categories');
    }
    

    public function description(){
        return $this->hasOne(CategoryDescription::class, 'category_id')->where('language_id','=', 1);
    }

CategoryDescription model - category names with descriptions in different languages ​​are stored here
protected $table = 'category_descriptions';

    protected $fillable = [
        'category_id','language_id','name','description','meta_title','meta_description','meta_keyword'
    ];


how to reduce the number of queries to the database and speed up menu processing, without a cache yet?

Created by provider

public function boot()
    {
        View::composer(['layouts.app'], function ($view){

            $view->with([
                'categories' =>  Category::where('parent','=',0)->with('childrens')->get(),
            ]);
        });
    }


and when I display the menu
@foreach($categories as $category)
                            <li class="_sidebar-menu_item">
                                <a href="#menu-{{$category->id}}" class="_sidebar-menu_link">
                                <span class="_sidebar-menu_img">
                                    <img src="{{$category->image}}" alt="{{$category->description['name']}}">
                                </span>
                                    <span class="_sidebar-menu_txt">{{$category->description['name']}}</span>
                                </a>
                            </li>
                        @endforeach


it turns out a lot of requests to the database, and I only brought out 2 parent categories
5ed190158fc71587067154.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rst630, 2020-09-09
@rst630

With one request, take all categories from the database and build a tree in php through a recursive function.
Here is an example Laravel Category Tree. How to reduce the number of queries in the database?
You can use the package https://github.com/staudenmeir/laravel-adjacency-l... - you need the descendants() method - this is convenient because you can take a category of any level and build a tree deeper, only by the number of requests I won’t suggest this package, test it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question