DB :: count()在laravel中不起作用

时间:2017-07-25 06:24:12

标签: laravel laravel-query-builder

我尝试获取laravel中的列总数,但它给出了不同的结果,我的查询如下所示。

$sub = DB::table('purchase_payments')
        ->where('bill',"")
        ->where('round',1)
        ->where('final',0)
        ->where('calculate_payment',0)
        ->where('bill_avg_date', '<' , $today)
        ->distinct('bill_link')
        ->count();

之后,我使用DB::raw尝试,但它给我一个语法错误

$due = DB::table('purchase_payments')
        ->count(DB::raw('DISTINCT bill_link  where `bill` = "" AND `round` = 1 AND `final` = 0 AND `calculate_payment` = 0 AND `bill_avg_date` < ' . $today));

错误: enter image description here

请帮助我实现正确计数。

4 个答案:

答案 0 :(得分:0)

我认为这里的查询形成是错误的。你能查看这里生成的查询吗?

DB::enableQueryLog();
$due = DB::table('purchase_payments')
    ->count(DB::raw('DISTINCT bill_link  where `bill` = "" AND `round` = 1 AND `final` = 0 AND `calculate_payment` = 0 AND `bill_avg_date` < ' . $today));
print_r(DB::getQueryLog());

这将打印您当前的查询。可能存在一些语法缺失

答案 1 :(得分:0)

您应该尝试此查询

       $query=DB::table('purchase_payments as pp')
        ->select(DB::raw('COUNT(DISTINCT(pp.bill_link)) as bill_count'))
        ->where('pp.bill',"")
        ->where('pp.round',1)
        ->where('pp.final',0)
        ->where('pp.calculate_payment',0)
        ->where('pp.bill_avg_date', '<' , $today)
        ->get()

答案 2 :(得分:0)

对于raw查询,必须引用日期:

... AND `calculate_payment` = 0 AND `bill_avg_date` < "' . $today . '"'));

答案 3 :(得分:0)

你应该尝试这个..如果你使用groupby或distinct

,你需要指定你想要计算的内容
$sub = DB::table('purchase_payments')
        ->where('bill',"")
        ->where('round',1)
        ->where('final',0)
        ->where('calculate_payment',0)
        ->where('bill_avg_date', '<' , $today)
        ->distinct('bill_link')
        ->count('bill_link');   <---
相关问题