aggregate methods of laravel

 n Laravel's Query Builder, you can use various aggregate methods to perform calculations on your query results. These methods allow you to retrieve aggregate values such as count, sum, average, maximum, minimum, etc. Here are some commonly used aggregate methods:

  1. count(): Returns the number of records matching the query.
$count = DB::table('users')->count();

  1. sum(): Returns the sum of a specified column's values.
php
$total = DB::table('sales')->sum('amount');
  1. avg(): Returns the average value of a specified column.
php
$average = DB::table('products')->avg('price');
  1. max(): Returns the maximum value of a specified column.
php
$maxPrice = DB::table('products')->max('price');
  1. min(): Returns the minimum value of a specified column.
php
$minPrice = DB::table('products')->min('price');
  1. groupBy(): Groups the results by a specified column.
php
$results = DB::table('orders') ->select('status', DB::raw('count(*) as total')) ->groupBy('status') ->get();
  1. having(): Applies a condition to the result of a group.
php
$results = DB::table('orders') ->select('status', DB::raw('count(*) as total')) ->groupBy('status') ->having('total', '>', 10) ->get();

These are just a few examples of the aggregate methods available in Laravel's Query Builder. You can refer to the Laravel documentation for a comprehensive list of aggregate methods and their usage: Laravel Query Builder - Aggregates





In Laravel's Query Builder, the having and where methods are used to apply conditions to your queries, but they have distinct purposes depending on the context. where method: The where method is used to apply conditions to filter the rows returned by a query. It is typically used with non-aggregate queries to filter the records before the grouping or aggregation is applied. The where method is applied before the groupBy or aggregate methods in the query builder. For example, to retrieve users with an age greater than 18: php Copy code $users = DB::table('users') ->where('age', '>', 18) ->get(); having method: The having method is used to apply conditions to the grouped or aggregated data. It is used with aggregate queries when you want to filter the groups or aggregated values based on certain conditions. The having method is applied after the groupBy or aggregate methods in the query builder. For example, to retrieve orders with a total greater than 100: php Copy code $orders = DB::table('orders') ->select('user_id', DB::raw('SUM(amount) as total')) ->groupBy('user_id') ->having('total', '>', 100) ->get(); In summary, the where method is used for filtering individual records before grouping or aggregation, while the having method is used for filtering groups or aggregated values based on conditions.

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...