Home > Net >  Laravel eloquent group by with 3-table join
Laravel eloquent group by with 3-table join

Time:12-22

I've been hacking away at this for hours, but can't work out how to resolve it.

Table structures are:

Plans:

  • id
  • title

Features:

  • id
  • title

FeatureTerms:

  • id
  • text
  • plan_id
  • feature_id

What I'd like to end up with is:

[{
  "plan_id": 1,
  "title": "Plan 1",
  "features": [
    {
      "title": "Feature 1",
      "term": "Term 1"
    },
    {
      "title": "Feature 2",
      "term": "Term 2"
    } 
  ]
},{
  ...
}]

Any help would be much appreciated

Regards, Andy

CodePudding user response:

It was more straightforward than I thought:

$plans = Plan::with("featureTerms.feature")->get();

CodePudding user response:

You should define Has Many Through relationship on Plan like this

public function features()
{
    return $this->hasManyThrough(Features::class, FeatureTerms::class);
}

After you have define relationship you can return plan with features eager loaded like this

$plan = Plan::with(["features"])->first();

This will return the first plan with related features

  • Related