我正在使用 Larvel 5.6,我的表名为 projects,包含以下列
id projectName type
1 abc finance
2 sxc marckting
3 dgt IT
4 hng finance
5 hng IT
6 gtf finance
etc
现在我需要计算每种类型的项目表的数量并将其打印在 welcome.blade.php 文件中,如下所示
finance(3) marckting(1) IT(2) etc
如何做到这一点?
最佳答案
你可以这样做:
$projects = Project::groupBy('type')->select('id', 'type', \DB::raw('COUNT(*) as cnt'))->get();
您可以像这样从您的 Controller 将变量传递给 Blade 模板:
return $this->view('welcome', compact('projects'));
最后,您像这样在欢迎 Blade 模板上对其进行迭代:
@foreach($projects as $project)
{{ $project->type }} ({{ $project->cnt }})
@endforeach
您可以确定“welcome.blade.php”文件位于正确的路径中。
关于php - 如何在 welcome.blade.php 中打印表列值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52458121/