Laravel Eloquent Eager Load Sums

时间:2018-05-18 18:22:25

标签: laravel eloquent sum eager-loading

我在加载页面之前使用预先加载来加载数据,以加快加载时间。

$websites = Website::with('valid_click_ads',
                          'facebook_ads',
                          'google_ads')->get();

我想知道是否有办法以这种方式获得列汇总。例如:

$websites = Website::with('valid_click_ads:sum(clicks),sum(revenue)',
                          'facebook_ads:sum(clicks),sum(impressions)',
                          'google_ads:sum(clicks),sum(impressions)')->get();

这会使加载时间更好!谢谢!

1 个答案:

答案 0 :(得分:2)

没有这样的东西,但你可以使用withCount方法作为这样的总和包装:

$websites = Website::withCount(['valid_click_ads'=>function($query){
                         $query->select( DB::raw( "COALESCE(SUM(clicks),0)" ) );
                       },
                      'facebook_ads'=>function($query){
                         $query->select( DB::raw( "COALESCE(SUM(clicks),0)" ) );
                       },
                      'google_ads'=>function($query){
                         $query->select( DB::raw( "COALESCE(SUM(clicks),0)" ) );
                       }])->get();

COALESCE是一个返回sum的SQL函数,如果存在,则返回0而不是返回null。

更新: 如果要检索单独的求和列,则必须为每个求和列定义索引,并将它们设为别名:

$websites = Website::withCount(['valid_click_ads as firstRes'=>function($query){
                     $query->select( DB::raw( "COALESCE(SUM(col1),0)" ) );
                   },
                   'valid_click_ads as secondRes'=>function($query){
                     $query->select( DB::raw( "COALESCE(SUM(col2),0)" ) );
                   }
                  ])->get();

等。