How to select from subquery using Laravel Query Builder? | Laravel Point

 

How to select from subquery using Laravel Query Builder?

In Laravel, you can use the query builder to select from a subquery using the select method on a query builder instance. Here's an example:

       $subquery = \DB::table('orders')
               ->selectRaw('sum(total) as total_sales')
               ->whereRaw('orders.user_id = users.id');

         $users = \DB::table('users')
            ->select('users.*', \DB::raw("({$subquery->toSql()}) as total_sales"))
            ->mergeBindings($subquery)
            ->get();

 

This will retrieve all the records from the users table, and include an additional total_sales column that contains the total sales for each user (calculated by summing up the total column of the orders table where the user_id matches the id of the user). The selectRaw method is used to specify a raw expression in the subquery, and the toSql method is used to retrieve the raw SQL string for the subquery. The mergeBindings method is used to merge the bindings from the subquery into the main query, so that all the bindings are correctly passed to the database when the query is executed.

Previous Post Next Post

Contact Form