【问题标题】:Laravel Eloquent group by relationLaravel Eloquent 按关系分组
【发布时间】:2017-04-20 19:02:30
【问题描述】:

我很难理解如何使用 Eloquent/Query Builder 处理关系。

我有以下几点:

$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();

我想按creator_id 分组,但我仍然只得到一个数据集合。

我做错了什么?

【问题讨论】:

    标签: php laravel eloquent query-builder


    【解决方案1】:

    改成

    $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();
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2021-07-14
      • 1970-01-01
      • 2016-10-15
      • 1970-01-01
      • 2016-09-26
      相关资源
      最近更新 更多