belipero
3 months ago
508
4
Laravel

Counting record with hasManyThrough and withCount

Posted 3 months ago by belipero

Hi! I have read many articles about counting records in relationships but i'm having a problem. I have a User model whichs is related to OfferDemand model (1:M) and this one related to OfferDemandMatchs (1:M)

In my user model I have declared the relationships

 public function offerdemands()
     {
         return $this->HasMany(Offerdemand::class);
     }

  public function offerdemandsmatchs()
      {
          return $this->hasManyThrough('App\Offerdemand', 'App\Offerdemandsmatchs');
       }

I want to retrieve each OfferDemannd record with OfferDemandMatchs count nested into each record.

With the following statement I retrieve all OfferDemand records for the user logged in:

  public function getdata()
    {
        $matchs = User::find(1)->offerdemands;
         return response()->json($matchs);
     }

I tried the following statements options but I'm not having the expected result:

$matchs = User::find(1)->offerdemand()->withCount('offerdemandsmatchs');
$matchs->withCount('offerdemandsmatchs')->get();
$matchs = User::find(1)->offerdemand->withCount('offerdemandsmatchs');

Does anyone knows how I can achieve the expected result?

Regards

Please sign in or create an account to participate in this conversation.