M
M
Max2020-11-24 15:06:05
Laravel
Max, 2020-11-24 15:06:05

How to leave only those categories (and its parent) in which there are records?

There are categories and subcategories. Made I use SimpleTree.
Subcategories can have entries. (Entries are a separate model)

How to keep only those subcategories and their parents(categories) that have certain entries?

So everything works correctly, but only subcategories:

$query-> where( function ($query) use($type_radio) {
                            $query->whereHas('record', function ($query) use($type_radio) { 
                                $query->where('type', $type_radio);
                            });
                        })->get();


I tried to add orWhere and iterate there using the map method, but for some reason it does not change the query:
orWhere( function ($query) use($type_radio) { 
                            $query->
                                whereHas('record', function ($query) use($type_radio) { 
                                     $query->where('type', $type_radio);
                                 })->
                                get()->map(function ($query ) { 
                                    $query = $query->parent()->get(); 
                                    Log::info($query ); 
                                    return $query;
                                });
                        })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sanes, 2020-11-24
@Sanes

public function index()
    {
        $categories = Category::withCount('posts')->orderByDesc('posts_count')->get();
        return view('blog.category-index', ['categories' => $categories]);
    }

In the template, filter by condition.
@if($category->posts_count === 0)
<a href="#" class="uk-icon-link" uk-icon="trash" onclick="deleteCategory({{ $category->id }}, '{{ $category->title }}');"></a>
<form action="{{ route('category.destroy', $category->id) }}" method="post" id="destroy-{{ $category->id }}">
  @csrf
</form>
@endif

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question