简体   繁体   English

一个雄辩的查询的多个总计

[英]Multiple totals with one eloquent query

Is it possible to get multiple totals from a database table?是否可以从数据库表中获取多个总计?

Table:桌子:

ID ID is_active活跃 clicks点击次数 impressions印象
n n true or.真或。 false错误的 int整数 int整数

Currently I have two queries:目前我有两个疑问:

$total_1 = Model::where('is_active', 1)->sum('clicks'); // output 2.000
$total_2 = Model::where('is_active', 1)->sum('impressions'); // output 8.000

You can do that with raw query:您可以使用原始查询做到这一点:

$data = Model::selectRaw('sum(clicks) as clicks, sum(impressions) as impressions')
    ->where('is_active', true)
    ->first();

$total_1 = $data->clicks ?? 0;
$total_2 = $data->impressions ?? 0;

https://laravel.com/docs/8.x/queries#raw-methods https://laravel.com/docs/8.x/queries#raw-methods

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM