从控制器返回项目总和的最佳实践

时间:2015-01-02 04:14:59

标签: php laravel laravel-4 blade

我有一个控制器,可以返回如下发票清单:

public function show()
{
    //list all invoices
    $invoices = DB::table('invoices')
        ->join('contacts','invoices.client_id','=','contacts.id')
        ->join('invoice_items','invoices.id','=','invoice_items.invoice_id')
        ->select('*')
        ->get(); //retrieve approved users
    return View::make('dashboard/invoices/list',
        array('invoices' => $invoices));
}

我希望能够显示invoice_items表的总和,其中invoice_id对应于invoices.id。完成此任务的最佳做法是什么?我应该编写另一种方法并在刀片模板中调用它吗?还是有一些更优雅的解决方案?

1 个答案:

答案 0 :(得分:0)

试试这个。

您可以使用Eloquent中的groupByDB::raw()方法来执行COUNT

public function show()
{
    //list all invoices
    $invoices = DB::table('invoices')
        ->join('contacts','invoices.client_id','=','contacts.id')
        ->join('invoice_items','invoices.id','=','invoice_items.invoice_id')
        ->groupBy('invoices.id')
        ->select(
            array('invoices.id', DB::raw('count(*) AS cnt_items'))
        )
        ->get();
    return View::make('dashboard/invoices/list',
        array('invoices' => $invoices));
}

或者,我建议您使用预先加载http://laravel.com/docs/4.2/eloquent#eager-loading