计算查询中的行数



Web View

我正在尝试计算列出的每种药物的总数,并按每种药物的总数进行细分,然后按位置进行汇总。所有这些数据都在一个表中。我用来获取每种药物的控制器如下。我正在尝试确定我是否必须为我正在寻找的每个计数编写一个查询,或者我是否需要为每个计数函数执行 php 计数函数,或者 laravel 是否有一些东西可以减少耗时?

enter code here public function index()
{
$medications = ControlledSubstances::with('Medications', 'Locations')->paginate('10');
$rx = Medications::where('controlled', '1')->get()
->keyBy('id')
->map(function ($rx){
return"{$rx->trade_name}  -  {$rx->brand_name}";
});
$cs = Medications::get();
$nb = NarcoticBoxes::get()
->keyBy('id')
->map(function ($nb){
return"{$nb->box_number}";
});
$status = VialStatus::get()
->keyBy('id')
->map(function ($status){
return"{$status->label}";
});
return view('logistics.controlled', compact('medications', 'rx', 'nb', 'status', 'cs'))->with('success', 'New Controlled Substance Added');
}
$mcount = ControlledSubstances::
select('medication', DB::raw('count(*) as count'), DB::raw('count(IF(status = 3,1,NULL)) safe'), DB::raw('count(IF(status = 4,1,NULL)) box'), DB::raw('count(IF(status = 8,1,NULL)) destroyed') ) 
->groupBy('medication')
->get();

引用Laravel 5 Docs:

$price = DB::table('orders')
->where('finalized', 1)
->avg('price');

然后将avg('price')更改为count()将为您提供计数。

或者:

$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();

最新更新