我是Laravel的新手,我需要你的帮助。
这在我的控制器上运行,只要我在同一表中有 3 行具有该标题,结果应该是"3"。
$countcategories = DB::table('categories')
->select(DB::raw('count(title) as result'))
->where('title','=','dsds')
->get();
我正在将查询结果传递给视图,如下所示->with('counts', $countcategories)
现在我的问题是:
- 在视图中,我只能通过使用
foreach
来显示结果。为什么?我的查询只返回一行。 - 我想将查询结果存储在控制器内的变量中,以便使用该结果。我该怎么做?
谢谢!
你应该使用 ->first() 方法:
$countcategories = DB::table('categories')
->select(DB::raw('count(title) as result'))
->where('title','=','dsds')
->first();
- 您
get
的是结果中的行,它在您的情况下只有一个。 - 你已经这样做了。
无论如何,这是我的方法:
// The result
$categories = Category::where('title','=','dsds');
foreach( $categories->all() as $category ) {
echo $category->title . "'n";
}
// The count
echo $categories->count();