skip to Main Content

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?

2

Answers


  1. 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()
        ];
    });
    
    Login or Signup to reply.
  2. 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 StaudenmeirEloquentHasManyDeepHasRelationships;
     
        public function comments()
        {
            return $this->hasManyDeep('AppComment', ['AppUser', 'AppPost']);
        }
    }
    

    Haven’t tested it though

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search