search
HomePHP FrameworkLaravelAn article explaining in detail how Laravel uses aggregate functions to calculate totals (with code examples)

This article brings you relevant knowledge about Laravel. It mainly introduces how to use conditional aggregate functions to calculate the total in Laravel. Let’s take a look at it together. I hope it will be helpful to friends who need it. help.

An article explaining in detail how Laravel uses aggregate functions to calculate totals (with code examples)

If there is an email subscription service, you want to display the detailed statistics page of the subscribers as shown below

Total number of subscribers Confirmed Unconfirmed Cancelled Bounced
200 150 50 10 5

For the purposes of this article, assume we have a subscribers database table containing data in the following format:

##小明adam@hotmeteor.comconfirmed小红taylor@laravel.comunconfirmed##小Jun##小花adam.wathan@gmail.combouncedWhat most people do:
name email status
jonathan@reinink.ca cancelled
$total = Subscriber::count();
$confirmed = Subscriber::where('status', 'confirmed')->count();
$unconfirmed = Subscriber::where('status', 'unconfirmed')->count();
$cancelled = Subscriber::where('status', 'cancelled')->count();
$bounced = Subscriber::where('status', 'bounced')->count();
The above will definitely produce five statements, which is definitely not good. So if you try to optimize it, you will use another method to solve the problem of executing multiple statements:

$subscribers = Subscriber::all();
$total = $subscribers->count();
$confirmed = $subscribers->where('status', 'confirmed')->count();
$unconfirmed = $subscribers->where('status', 'unconfirmed')->count();
$cancelled = $subscribers->where('status', 'cancelled')->count();
$bounced = $subscribers->where('status', 'bounced')->count();

The above first obtains all subscriber data, and then performs conditional statistics on this result set, using

Collection

. Model multiple data queries return

Illuminate\Database\Eloquent\Collection. This method is only suitable for use when the amount of data is not large. If our application has thousands or millions of subscribers, the processing time will be very slow and a large amount of memory will be used. Conditional Aggregation

There is actually a very simple way to query and calculate these totals. The trick is to put the condition in an aggregate function. Here is a SQL example:

select
  count(*) as total,
  count(case when status = 'confirmed' then 1 end) as confirmed,
  count(case when status = 'unconfirmed' then 1 end) as unconfirmed,
  count(case when status = 'cancelled' then 1 end) as cancelled,
  count(case when status = 'bounced' then 1 end) as bounced
from subscribers

 total | confirmed | unconfirmed | cancelled | bounced
-------+-----------+-------------+-----------+---------
   200 |       150 |          50 |        30 |      25

————————————————
原文作者:4pmzzzzzzzzzz
转自链接:https://learnku.com/articles/74652
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。

Here is how to write this query in Laravel using the query builder:

$totals = DB::table('subscribers')
    ->selectRaw('count(*) as total')
    ->selectRaw("count(case when status = 'confirmed' then 1 end) as confirmed")
    ->selectRaw("count(case when status = 'unconfirmed' then 1 end) as unconfirmed")
    ->selectRaw("count(case when status = 'cancelled' then 1 end) as cancelled")
    ->selectRaw("count(case when status = 'bounced' then 1 end) as bounced")
    ->first();

<div>Total: {{ $totals->total }}</div>
<div>Confirmed: {{ $totals->confirmed }}</div>
<div>Unconfirmed: {{ $totals->unconfirmed }}</div>
<div>Cancelled: {{ $totals->cancelled }}</div>
<div>Bounced: {{ $totals->bounced }}</div>

Boolean Column (Field)

Table migration creates boolean

fields,

model definition belongs to transformation The model is not used as a code example here, you can replace it with modelIf you use boolean

When the fields are listed, it will be easier, for example, to query whether the users in the

subscribers table have different role permissions. Assume that the subscribers table has is_admin, is_treasurer, is_editor, is_manager, and fields

$totals = DB::table(&#39;subscribers&#39;)
    ->selectRaw(&#39;count(*) as total&#39;)
    ->selectRaw(&#39;count(is_admin or null) as admins&#39;)
    ->selectRaw(&#39;count(is_treasurer or null) as treasurers&#39;)
    ->selectRaw(&#39;count(is_editor or null) as editors&#39;)
    ->selectRaw(&#39;count(is_manager or null) as managers&#39;)
    ->first();
This is because the aggregate function count

ignores

null columns. Unlike false || null in PHP which returns false, in SQL (and JavaScript) it returns null. Basically, A || B returns the value A if A can be coerced to true; otherwise, B is returned. If you don’t understand this paragraph, please read my explanation below: Using laravel’s

boolean

column, the field in the actual data table is
tinyint, and the value is 0(false) and 1(true), for example, Xiao Ming’s is_admin field is
1(true),count(is_admin or null) can be regarded as expressed as (1 or null), if A is true, it returns A, and the final sql is count(is_admin). On the contrary, if the is_admin field is
0(false), and the final sql is count(null), then this column will be ignored

//PHP  返回 false
var_dump(0 || null) 

//JavaScript 返回 null
console.log(0 || null)

//SQL 返回 null
SELECT (0 or null) as result
Translation of the original text

: This article is just a translation of the general meaning, and is used as a simple record for myself

Recommended study: "laravel video tutorial

"

The above is the detailed content of An article explaining in detail how Laravel uses aggregate functions to calculate totals (with code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Which is better PHP or Laravel?Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

Is Laravel a frontend or backend?Is Laravel a frontend or backend?Mar 27, 2025 pm 05:31 PM

LaravelisabackendframeworkbuiltonPHP,designedforwebapplicationdevelopment.Itfocusesonserver-sidelogic,databasemanagement,andapplicationstructure,andcanbeintegratedwithfrontendtechnologieslikeVue.jsorReactforfull-stackdevelopment.

How do I create and use custom Blade directives in Laravel?How do I create and use custom Blade directives in Laravel?Mar 17, 2025 pm 02:50 PM

The article discusses creating and using custom Blade directives in Laravel to enhance templating. It covers defining directives, using them in templates, and managing them in large projects, highlighting benefits like improved code reusability and r

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools