Skip to content

Instantly share code, notes, and snippets.

@RomikMakavana
Last active November 22, 2021 10:16
Show Gist options
  • Save RomikMakavana/5a72592333ef24a8ba69270e50315242 to your computer and use it in GitHub Desktop.
Save RomikMakavana/5a72592333ef24a8ba69270e50315242 to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
class Utils extends Model
{
public static function getQueryGroupConcat($keyValues, $distinct = false){
$groupConcat = ["'{'"];
$vals = [];
foreach ($keyValues as $key => $value) {
$k = (string)Str::of('\'"?": \'')->replaceArray('?', [$key]);
$v = (string)Str::of("JSON_QUOTE(IFNULL(?,''))")->replaceArray('?', [$value]);
$vals[] = $k . "," . $v;
}
$vals = implode(",',',", $vals);
$groupConcat[] = $vals;
$groupConcat[] = "'}'";
if($distinct == true){
$query = "CONCAT( '[', GROUP_CONCAT( DISTINCT CONCAT(". implode(',', $groupConcat ) .") SEPARATOR ',') ,']' )";
}else{
$query = "CONCAT( '[', GROUP_CONCAT( CONCAT(". implode(',', $groupConcat ) .") SEPARATOR ',') ,']' )";
}
return $query;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment