计数查询laravel中的行

时间:2018-10-04 23:56:56

标签: php laravel-5 eloquent

Web View

我正在尝试计算列出的每种药物的总数,然后将其按每种药物的总数进行细分,然后按位置进行汇总。所有这些数据都在一个表中。我用来获取每种药物的控制器如下。我正在尝试确定是否要为我要查找的每个理货编写查询,还是我需要为每个理货做一个php count函数,还是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');
}

2 个答案:

答案 0 :(得分:1)

$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();

答案 1 :(得分:0)

引用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();