如何在 Laravel 查询生成器中计算 'where' 匹配的记录

How to count 'where' matched records in Laravel query builder

我正在研究查询生成器。 下面的代码有效,我可以获得计数,但是 $calccount 部分看起来很奇怪。

HTML观点是这样的

[{"count(*)":13}]

你能教我写代码吗?

 public function s_list()
 {
     $books = DB::table('books')  //This is works
     ->where('q18a', '=', '5')
     ->get();
     
     $ttlrecordC = Book::count('kid'); //This is works

     $calccount = DB::table('books') //works but looks strange
     ->select(DB::raw('count(*)'))
     ->where('q18a', '=', '5')
     ->get();

     return view('s_list', ['books' =>$books])
     ->with('ttlrecordC',$ttlrecordC)
     ->with('calccount',$calccount);
 }

使用 calc 方法代替 get

$calccount = DB::table('books') 
     ->where('q18a', '=', '5')
     ->count();
//if you have models in place
$calccount = Book::where('q18a', '=', '5')->count();

对于 return 视图,您可以这样做

 return view('s_list', [
    'books' => $books,
    'ttlrecordC' => $ttlrecordC,
    'calccount' => $calccount,
]);