我需要计算同一个表中的几个值。我目前正在重复每个查询并仅修改
where()
子句。这可行,但几乎没有使用 DRY 方法。
在我的控制器中,这是我当前调用返回每个所需计数的方法:
$one = DB::table('stores')->where('store_id', '1')->count();
$two = DB::table('stores')->where('store_id', '2')->count();
$three = DB::table('stores')->where('store_id', '3')->count();
$four = DB::table('stores')->count();
$dutch = DB::table('stores')->where('country', 'Netherlands')->count();
$swedish = DB::table('stores')->where('country', 'Sweden')->count();
return View::make('retailers.index', compact('one','two','three', 'four', 'dutch','swedish'));
我的看法,我这样称呼:
{{ $one }}, {{ $two }}, {{ $three }} etc etc
是否有一种更合适的方法,然后必须对一个表的每个计数进行查询?任何解决方案将不胜感激。
您可以使用以下查询:
$results= DB::table('stores')
->select('store_id', DB::raw('count(*) as count'))
->groupBy('store_id')
->get();
现在在您的视图中,您可以循环浏览它。
@foreach($results as $result)
{{ $result->store_id }}
{{ $result->count }}
@endforeach
你可以按照以下方式运行一些东西
SELECT count(*), store_id FROM myTable GROUP BY store_id
根据需要进行任意数量的条件 SUM() 聚合函数调用,然后在视图中访问该平面对象。
代码:(PHPize演示)
$data = $db::table('stores')
->selectRaw('SUM(store_id = 1) one')
->selectRaw('SUM(store_id = 2) two')
->selectRaw('SUM(store_id = 3) three')
->selectRaw('COUNT(1) total')
->selectRaw("SUM(country = 'Netherlands') dutch")
->selectRaw("SUM(country = 'Sweden') swedish")
->first();
return view('retailers.index')->with('data', $data);
$data
的结构如下:
(object) array(
'one' => '4',
'two' => '3',
'three' => '1',
'total' => 8,
'dutch' => '3',
'swedish' => '2',
)
然后在您的视图中,您可以单独访问每个属性名称和值,或者使用
foreach()
循环遍历结构。