你好我有两个表,另一个是ads_listings。在类别表中有4列id,parent_category_id,category_slug,category_title。这里parent_category_id 0表示主要类别,其余部分表示子类别。 ads_listings表中的用户发布商店。现在我想查找具有此类特定类别的帖子
vehicles(3)
cars(2)
motorbike(1)
cycle(0)
这里的问题是我的代码只找到了有帖子的子类别。我的控制器代码是
public function countListingsByCategories()
{
return DB::table("ads_listings")
->select("categories.category_title",DB::raw("COUNT(ads_listings.category_id) as num_listings"))
->join("categories", "categories.id","=","ads_listings.category_id")
->groupBy("ads_listings.category_id")
->get();
}
查看代码是:
<ul class="row catelist">
@if(isset($categoriesNumListings) && count($categoriesNumListings))
@foreach($categoriesNumListings as $categoriesNumListings)
<li class="col-md-12"><a href="{{ route('view.listings.by.category', $categoriesNumListings->category_title) }}" title="{{ $categoriesNumListings->category_title }} ads from {{ $categoriesNumListings->category_title }}">{{ $categoriesNumListings->category_title }} <span>({{ $categoriesNumListings->num_listings }}Listings )</span></a></li>
@endforeach
@endif
</ul>
我的分类表是:
ads_listing表是:
答案 0 :(得分:0)
我认为问题在于,当您主要想要计算类别并获取ad_listings的数量时,您在计算ad_listings,我会做类似的事情:
第二枪:)
public function countListingsByCategories()
{
return DB::table("categories")
->select("categories.category_title",
DB::raw("categories.title,
CASE
WHEN (categories.parent_id = 0)
THEN (SELECT count(ads_listings.category_id)
FROM ads_listings
WHERE ads_listings.category_id in
(SELECT subcategory.id
FROM categories subcategory
WHERE subcategory.parent_id = categories.id))
ELSE (SELECT COUNT(ads_listings.category_id)
FROM ads_listings
WHERE ads_listings.category_id = categories.id)
END as numberOfPosts,
CASE
WHEN (categories.parent_id = 0)
THEN (select 'Category')
ELSE (select 'subCategory')
END as type
FROM categories"))
->get();
}