在Laravel雄辩中可以使用一个GroupBy子句的with函数吗? [英] Can the with function be used with a GroupBy clause in Laravel Eloquent?
问题描述
可以在Laravel雄辩中将with函数与GroupBy子句一起使用吗?
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?
以下是我目前拥有的查询
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')));
订单
表具有列名称 campaign_id
其中 belongsTo
名为广告系列
的表。我想从每个广告系列获得订单表中的销售总数,需要以下列方式显示。
The order
table has a column name campaign_id
which belongsTo
the 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.
Total Sales Campaign
-------------------------
200 Campaign1
500 Campaign2
300 Campaign3
如果我必须执行特定的选择,或者我可以访问Campaign表的值以上查询?
Should I have to perform a specific select or can I access the values of the Campaign table from the above query?
推荐答案
如果With函数中指定的Model所需的引用列在 SELECT
子句,则上述查询考虑了与
函数。纠正的查询将是
If the referenced column required by the Model specified on the With function is retrieved in the SELECT
clause, then the With
function is taken into consideration by the above query. The rectified query will be
$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'));
这样可以使用
foreach($groupedSalesCampaign as $campaign)
{
Log::info($campaign->foo->bar);
}
已编辑。
这篇关于在Laravel雄辩中可以使用一个GroupBy子句的with函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!