问题描述:

I have a scenario where I need to group by my results from the database based on conditions from the UI. The example on the Laravel docs shows that I can perform groupBy like this:

$query->groupBy('col1','col2','col3');

But how do I do this if I want this to be conditional? Will the following work?

$query->groupBy(function($query){

if($allowCol1 == true)

$query->groupBy('col1');

if($allowCol2 == true)

$query->groupBy('col2');

})->get();

网友答案:

In this way you can

$query = Model::with('eagerload');
if($allowCol1 == true) $query->groupBy('col1');
if($allowCol2 == true) $query->groupBy('col2');
$variable = $query->get();
相关阅读:
Top