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

14,655

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'));

This way the Campaign information can be retrieved using

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

Edited.

Share:
14,655

Related videos on Youtube

Abishek
Author by

Abishek

Experienced and an influential Technical Leader and Architect, an inspirational leader who effectively manages, develops and motivates internal & external teams. Strong ability to quickly understand and analyze business strategies ensuring technology solutions meet business requirement, to quickly adapt to all new technologies & challenges. Attention to detail, high technical aptitude and hands on approach together with a high degree of motivation and professionalism would make me an asset to any progressive organization or demanding position within IT industry. I spend a lot of time learning new stuff and I enjoy doing it.

Updated on June 04, 2022

Comments

  • Abishek
    Abishek almost 2 years

    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')));
    

    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
    

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