Search code examples
phpormeloquentlaravel-5.5

Eloquent request with subitems count


I have 2 tables :

  • Valuechains : id, created_at, updated_at, deleted_at
  • Segments : id, valuechain_id (Foreign key), created_at, updated_at, deleted_at

And pivot tables (not really important here).

I have a method with sql requests ...

  • $valuechains list gives me a list of all the value chains which are not (soft) deleted
  • $valuechainCount counts the number of valuechains which are published
  • $segmentCount counts the number of segments for each value chains

I try to use the map function in order to add a column which contains the number of segments for each value chains ...

public function vcListAndSegmentCount() {
    $valuechainLists = Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
        ->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
        ->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
        ->where('langs.isMainlanguage', '=', '1')
        ->whereNull('valuechains.deleted_at')
        ->get();

    $valuechainCount = Valuechain::whereNull('valuechains.deleted_at')->count();

    for ($i=0; $i < $valuechainCount; $i++) {
        $segmentCount[$i] = Segment::whereNull('segments.deleted_at')
            ->where('valuechain_id', '=', $valuechainLists[$i]->id)->count();
    }

    $valuechainLists = $valuechainLists->map(function ($record) use ($segmentCount) {
        $vclists = array_first($segmentCount, function ($value, $key) use ($record) {
            return $value['id'] === $record['valuechain_id'];
        });
        $record['count'] = $vclists;
        return $record;

    });
    dd($valuechainLists);
}

The map methods adds a column my output collection. Unfortunatelly, the new collection is not giving me the right numbers of segments for each value chain... it only adds one value ...

Here is what I obtain :

Collection {#380 ▼
  #items: array:4 [▼
    0 => Valuechain {#450 ▼
      ...
      #attributes: array:4 [▼
        "id" => 1
        "vcname" => "Génétique"
        "vcshortname" => "Génétique"
        "count" => 6
      ]
      #original: array:3 [▶]
      ...
    }
    1 => Valuechain {#451 ▼
      ...
      #attributes: array:4 [▼
        "id" => 2
        "vcname" => "Biotruc"
        "vcshortname" => "Biotruc"
        "count" => 6
      ]
      ...
    }
    2 => Valuechain {#452 ▼
      ...
      #attributes: array:4 [▼
        "id" => 3
        "vcname" => "VC3"
        "vcshortname" => "VC3"
        "count" => 6
      ]
      ...
    }
    3 => Valuechain {#453 ▼
      ...
      #attributes: array:4 [▼
        "id" => 4
        "vcname" => "VC4"
        "vcshortname" => "VC4"
        "count" => 6
      ]
      #original: array:3 [▶]
      ...
    }
  ]
}

I obtain 6, 6, 6 and 6 whereas the count should be 6, 5, 4, 4...


Solution

  • If you are using Laravel >= 5.2 and if you have defined the relationships on the models, you can use the withCount() method.

    It would go something like this:

     Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
        ->withCount(['segments' => function ($query) {
            $query->whereNull('deleted_at);
        }])
        ->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
        ->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
        ->where('langs.isMainlanguage', '=', '1')
        ->whereNull('valuechains.deleted_at')
        ->get()
    

    or if your Segment model uses the SoftDeletes trait, then it's a bit simpler:

    Valuechain::select('valuechains.id', 'lang_valuechain.vcname', 'lang_valuechain.vcshortname')
        ->withCount('segments')
        ->join('lang_valuechain', 'valuechains.id', '=', 'lang_valuechain.valuechain_id')
        ->join('langs', 'lang_valuechain.lang_id', '=', 'langs.id')
        ->where('langs.isMainlanguage', '=', '1')
        ->whereNull('valuechains.deleted_at')
        ->get()