with 函数可以与 Laravel Eloquent 中的 GroupBy 子句一起使用吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16763257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:49:27  来源:igfitidea点击:

Can the with function be used with a GroupBy clause in Laravel Eloquent?

group-bylaravellaravel-4eloquent

提问by Abishek

Can the with function be used with a GroupBy clause in Laravel Eloquent? Does it serve any purpose if I have specific items to select using the Select Clause?

with 函数可以与 Laravel Eloquent 中的 GroupBy 子句一起使用吗?如果我有特定的项目要使用选择条款来选择,它是否有任何用途?

Following is the query that I currently have

以下是我目前的查询

Order::with('Campaign')
            ->where('isapproved','=','Y')
            ->groupBy('campaign_id')
            ->orderBy(DB::raw('COUNT(id)','desc'))
            ->get(array(DB::raw('COUNT(id) as totalsales')));

The ordertable has a column name campaign_idwhich belongsTothe table named campaigns. I would like to get the total count of the sales from the order table against each campaign and need to show in the following manner.

order表有一个列名campaign_idbelongsTo该表名为campaigns. 我想从每个活动的订单表中获取销售总数,并需要以以下方式显示。

Total Sales     Campaign
-------------------------
  200            Campaign1
  500            Campaign2
  300            Campaign3

Should I have to perform a specific select or can I access the values of the Campaign table from the above query?

我应该执行特定的选择还是可以从上述查询访问 Campaign 表的值?

采纳答案by Abishek

If the referenced column required by the Model specified on the With function is retrieved in the SELECTclause, then the Withfunction is taken into consideration by the above query. The rectified query will be

如果在 With 函数上指定的 Model 所需的引用列在SELECT子句中检索到,则With上述查询会考虑该函数。更正后的查询将是

$groupedSalesCampaign = Order::with('Campaign')
            ->where('isapproved','=','Y')
            ->groupBy('campaign_id')
            ->orderBy(DB::raw('COUNT(id)','desc'))
            ->get(array(DB::raw('COUNT(id) as totalsales'),'campaign_id'));

This way the Campaign information can be retrieved using

这样,可以使用以下方法检索活动信息

foreach($groupedSalesCampaign as $campaign)
{
      Log::info($campaign->foo->bar);
}

Edited.

已编辑。