Home > other >  Convert raw query to laravel eloquent with sum function
Convert raw query to laravel eloquent with sum function

Time:12-07

DB::SELECT(
            "SELECT SUM(carts.quantity) as couuntq, carts.productid, products.name, products.name, products.price,products.gallary FROM carts,products  
            WHERE 
            carts.productid = products.id AND
            carts.userid = ".$userid ."
            GROUP BY carts.productid
            order by carts.productid"
)

I converted but not working with sum function

DB::table('carts')
        ->join('products','carts.productid','products.id')
        ->select('carts.quantity','carts.productid', 'products.name', 'products.name', 'products.price','products.gallary')
        ->where('carts.userid',$userid)
        ->groupBy('carts.productid')
        ->orderBy('carts.productid')
        ->sum('carts.quantity')
        ->get();

CodePudding user response:

Try this, add your sum aggregate method in raw along with your other required column names

DB::table('carts')
    ->join('products','carts.productid','=','products.id')
    ->Select(DB::raw('SUM(carts.quantity) as couuntq'), 'carts.productid', 'products.name', 'products.price', 'products.gallary')
    ->where('carts.productid','products.id')
    ->where('carts.userid',$userid)
    ->GroupBy('carts.productid')
    ->orderBy('carts.productid', 'asc')
    ->get();
  • Related