当前位置: 动力学知识库 > 问答 > 编程问答 >

mysql - conditional groupBy using Laravel

问题描述:

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();
分享给朋友:
您可能感兴趣的文章:
随机阅读: