Home > Net >  laravel - how to get list of 3rd level deep relation
laravel - how to get list of 3rd level deep relation

Time:12-31

My model structure is as follows:

Question
  hasMany Decision
    hasMany Impact
      morphTo Related

So I'm trying to get a list of Questions with all of their Related objects deep inside.

Example:

{'question':1, relateds:[obj, obj, obj]}
{'question':2, relateds:[obj, obj, obj]}
{'question':3, relateds:[obj, obj, obj]}

I tried hasManyThrought relation, but it only works with two deep levels.

How can I achieve it?

CodePudding user response:

Try

$questions = Question::with(['decisions.impacts.related'])->get();

or Something like

$questions = Question::all();

foreach ($questions as $question) {
    $question->load(['decisions.impacts.related']);
}

Didn't test.


Edit

foreach ($questions as $question) {
    $relateds = [];
    foreach ($question->decisions as $decision) {
        foreach ($decision->impacts as $impact) {
            $relateds[] = $impact->related;
        }
    }
    $result[] = ['question' => $question, 'relateds' => $relateds];
}

or

questions = Question::with('decisions.impacts.related')->get();

$result = $questions->map(function ($question) {
    return [
        'question' => $question,
        'relateds' => $question->decisions->pluck('impacts')->flatten()->pluck('related')->flatten()
    ];
});

CodePudding user response:

There is a package for this: https://laravel-news.com/hasmanydeep-package example usage: Country → hasMany → User → hasMany → Post → hasMany → Comment

class Country extends Model
{

    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
 
    public function comments()
    {
        return $this->hasManyDeep('App\Comment', ['App\User', 'App\Post']);
    }
}

Haven't tested it though

  • Related