Answer the question
In order to leave comments, you need to log in
Laravel count news in selected category (including subcategories)?
Hello, I can’t figure out how to get the number of ads in the selected category (including subcategories) through ORM:
There are categories and subcategories, for example:
Auto
-bwm
-audi
Moto
-irbis
-polaris there is a posts
table with ads , there is also a posts_categories
table
type: post_id | categories_id
and a table with categories categories id | name | parent
Can you please tell me how to get the number of ads in the selected category (including subcategories) through ORM? for example get the number of ads in the category Auto (count the number of ads from subcategories bwm and audi)
I only have an idea to first get a list of all subcategories like so:
$categories = Categories::where('parent', '=', $id)->get();
Answer the question
In order to leave comments, you need to log in
In haste, if I understand correctly, the output to the site:
@foreach(Categories::all() as $category)
{{ $category->name }} <span class="badge">{{ Post_categories::where('categories_id', $category->id)->count() }}</span>
@endif
class Categories extends Model {
public function posts()
{
//Получаем множество постов, опубликованных в категории
return $this->hasMany('App\PostCategories', 'categories_id', 'id');
}
}
public function index(){
//Получаем коллекцию категорий, где есть посты. Есть постов в категории нет, то ее не будет в выборке.
$categories = Categories::has('posts')->get();
return view('index', compact('categories'));
}
@foreach($categories as $category)
{{ $category->name }} <span class="badge">{{ $category->posts->count() }}</span>
@endif
It seems to me that it is possible to make Categories hasOne() on the parent category and count it as an option via eager loading. Or I misunderstood the question
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question