


An 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.
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:
name | status | |
---|---|---|
adam@hotmeteor.com | confirmed | |
taylor@laravel.com | unconfirmed | |
jonathan@reinink.ca | cancelled | ##小花 |
bounced |
$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();
$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();
Collection
. Model multiple data queries returnIlluminate\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 版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。
$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 thesubscribers table have different role permissions. Assume that the
subscribers table has
is_admin,
is_treasurer,
is_editor,
is_manager, and fields
$totals = DB::table('subscribers') ->selectRaw('count(*) as total') ->selectRaw('count(is_admin or null) as admins') ->selectRaw('count(is_treasurer or null) as treasurers') ->selectRaw('count(is_editor or null) as editors') ->selectRaw('count(is_manager or null) as managers') ->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
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 myselfRecommended 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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 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 ?

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.

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.

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.

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.

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.
