我需要从一张桌子上的不同查询中获得多个结果。 例如,我需要获取一张表的计数,总和,平均值。我应该这样做还是有更短的方法?
public function index()
{
$count = Patient::all()->count();
$dateCount = Patient::where('date', date("Y-m-d"))->count();
$loanAmount = DB::table('patients')->sum('loan_amount');
$payAmount = DB::table('patients')->sum('pay_amount');
return view('index', compact('count','dateCount','loanAmount' ,'payAmount'));
}
如果您看到所有查询都针对一个表以获取特定结果,那么基本上没有一种方法可以通过单个查询来获得这些结果吗?
答案 0 :(得分:0)
您可以执行以下操作。
public function index()
{
$patient = Patient::all();
$count = $patient->count();
$dateCount = Patient::today()->count();
$loanAmount = $patient->sum('loan_amount');
$payAmount = $patient->sum('pay_amount');
return view('index', compact('count','dateCount','loanAmount' ,'payAmount'));
}
您还可以在患者模型中创建范围:
public function scopeToday($query) {
return $query->where('date', date("Y-m-d"));
}
答案 1 :(得分:0)
您可以通过数据库查询执行以下操作:
$data=\DB::table('patients')
->selectRaw('count(id) as count,sum(loan_amount) as loanAmount,sum(pay_amount) as payAmount,sum(case when date = "'.date("Y-m-d").'" then 1 else 0 end) AS dateCount')
->first();
您也可以使用雄辩的方法执行此操作,但是它将返回您的收藏集。
$data=Patient::selectRaw('count(id) as count,sum(loan_amount) as loanAmount,sum(pay_amount) as payAmount,sum(case when date = "'.date("Y-m-d").'" then 1 else 0 end) AS dateCount')
->first();