Breezer
Breezer

Reputation: 10490

Get grandchildren to model with Laravel eloquent

I have following model Type->Categories->Task

Where Categories Can belong to different Types. Here I use morphTo in the Category Model

Category Model

class Category extends Model {


public function categorize(){
    return $this->morphTo();
}
public function tasks(){
    return $this->belongsToMany(Task::class,'task_category');
}
public function types(){
    return $this->belongsTo(Type::class);
}
}

And in Types I use morphMany

class Type extends Model
{
    //
    protected $fillable = [
        'slug'
    ];
    public function categories(){
        return $this->morphMany(Category::class,'categorize');
    }
    public function project(){
        return $this->belongsTo(Project::class);
    }
   /*  public function tasks(){
        return $this->hasManyThrough(
            Task::class,
            Category::class,

        );
    } */
}

This works as intended but I don't know how I within the taskcontroller could get all tasks depending on type and with all the categories, through the type model. I tried hasManyThrough but it doesn't work, since tasks and categories are related through a pivot table.

Currently I have

$type = Type::with('categories')->where('slug', $type)->first();

this gets me the type with categories, but as mentioned before I'd like to get associated tasks under each category object. If something is unclear I'll be happy to clearify and correct whatever is need. All help is very much appreciated.

Upvotes: 0

Views: 428

Answers (1)

Donkarnash
Donkarnash

Reputation: 12845

Laravel allows to eager load nested relations

$type = Type::with('categories.tasks')->where('slug', $type)->first();

Laravel docs: https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading

Upvotes: 2

Related Questions