Home > Blockchain >  Create variable based query to select data in laravel
Create variable based query to select data in laravel

Time:04-29

I created a helper function for count all notification in navbar, For this I am storing clause in a single variable.

I am accessing it by calling-

countData("notification","WHERE seen_status = '0'") 

My function is-

function countData($table,$clause) {
    $result = DB::select("SELECT * FROM $table $clause");
    return count($result);
}

It working fine, but getting error in-

countData("projects","GROUP BY user")

I can use groupBy('user') but problem is, I don't want to pass too many variable inside my function. So, is there any option to run my custom query by using single variable?

CodePudding user response:

I think your group by must have a specific column in your select.

try that


function countData($columns,$table,$clause) {
    $result = DB::select("SELECT $columns FROM $table $clause");
    return count($result);
}

countData("user","projects","GROUP BY user")

or you can simply make one variable for all your selects

function countData($query) { $result = DB::select($query); return count($result); } 

CodePudding user response:

The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.

So the problem here is that you need to use an aggregate function first then group it

  • Related