所以,我有一个看起来像这样的数据库表:
id | title | category | author | post | created_at | updated_at
类别列是文本值,因此当前具有“科技”、“网络”和“动物”等值。我需要做的是计算类别列中的每个类别值并获得如下输出:
Tech (2)
Animal (2)
Web (1)
现在,我确实可以使用它了。目前看起来像:
Tech (1) (1)
Animal (1) (1)
Web (1)
我的 Controller 中的查询是:
$categoryCount = Post::select(DB::raw('count(*) as cat_count, category'))
->groupBy('category')
->count();
我的 View 当前如下所示:
@if(count($category) > 0)
@foreach($category as $cat)
<a href="{{ URL('category/'.str_replace(' ', '-', $cat->name)) }}"
class="list-group-item">{{ $cat->name }}
@foreach($posts as $post)
@if($post->category == $cat->name)
({{ $categoryCount }})
@endif
@endforeach
</a>
@endforeach
@endif
我对 Laravel 本身还很陌生,所以我还在学习中。任何帮助实现我想要的目标将不胜感激。
最佳答案
您进行数据库原始计数,然后再次计数。它确实总是返回一。更改您的查询:
$categoryCount = Post::select(DB::raw('count(*) as cat_count, category'))
->groupBy('category')
->get();
你的结果应该是不同的。顺便说一句,这与 Laravel 无关,只是你计算一下:-)
关于php - 计算数据库列文本值 - Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37616344/