简体   繁体   中英

Laravel Eloquent group by relation

I'm struggling to understand how to use Eloquent/Query Builder with relationships.

I have the following:

$plantLots = PlantLot::with('controlNumber')
   ->whereHas('controlNumber', function ($q) use ($fromDate, $toDate) {
        $q->where('created_at', '>=', $fromDate);
        if($toDate != '') {
           $q->where('created_at', '=<', $toDate);
        }
        $q->groupBy('creator_id');
   })->get();

I want to group by creator_id , but I still just get a single collection of data.

What am I doing wrong?

change it to

$plantLots = PlantLot::with(['controlNumber' => function($q){
       $q->groupBy('creator_id');
   }])
   ->whereHas('controlNumber', function ($q) use ($fromDate, $toDate) {
     $q->where('created_at', '>=', $fromDate)
       ->when($toDate != '',function($q){
         $q->where('created_at', '=<', $toDate);
      });
  })->get();

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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