Join with sum in Laravel

Asked

Viewed 51 times

1

I am trying to bring a JSON result from my database.

 $products = DB::table('products')
    ->join('order_product', 'products.id', '=', 'order_product.product_id')
    ->select('products.sku', 'products.name', 'order_product.quantity')
    ->get();
    return response()->json($products);

Upshot

inserir a descrição da imagem aqui

What I’m willing to do now is add up the sold amount of each item, as I should do?

1 answer

4


I was able to perform the operation.

Follows code;

$products = DB::table('products')
    ->join('order_product', 'products.id', '=', 'order_product.product_id')
    ->select(DB::raw('products.sku, products.name, sum(order_product.quantity) as sales_quantity'))
    ->groupBy('products.sku')
    ->get();
    return response()->json($products);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.