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

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

Jan 20, 2023 pm 04:08 PM
laravel

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();
Copy after login
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();
Copy after login

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
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。
Copy after login

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>
Copy after login

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();
Copy after login
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
Copy after login
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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

Questions and Answers on PHP Enterprise Application Microservice Architecture Design Questions and Answers on PHP Enterprise Application Microservice Architecture Design May 07, 2024 am 09:36 AM

Microservice architecture uses PHP frameworks (such as Symfony and Laravel) to implement microservices and follows RESTful principles and standard data formats to design APIs. Microservices communicate via message queues, HTTP requests, or gRPC, and use tools such as Prometheus and ELKStack for monitoring and troubleshooting.

Laravel vs CodeIgniter: Which framework is better for small projects? Laravel vs CodeIgniter: Which framework is better for small projects? Jun 04, 2024 pm 05:29 PM

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

Which is the better template engine, Laravel or CodeIgniter? Which is the better template engine, Laravel or CodeIgniter? Jun 03, 2024 am 11:30 AM

Comparing Laravel's Blade and CodeIgniter's Twig template engine, choose based on project needs and personal preferences: Blade is based on MVC syntax, which encourages good code organization and template inheritance. Twig is a third-party library that provides flexible syntax, powerful filters, extended support, and security sandboxing.

See all articles