vendredi 29 juin 2018

Multilevel relationship whereHas on eloquent Model in Laravel

I'd like to find Project::with('tasks.tags')->find(2);

where only tasks with a particular id of tag return in the result set for a particular project.

For ex. I'd like to find a project with ID of 2 with all its tasks and tasks with tags with only id of 1.

I have tried various ways but have failed so far.

I have tried:

$project = Project::with('tasks.tags')->whereHas('tasks', function($query){
            $query->whereHas('tags', function($query) {
                $query->where('id', 1);
            });
})->find(1);

And:

$project = Project::with('tasks.tags')->whereHas('tasks', function($query){
            $query->whereHas('tags', function($query) {
                $query->where('tag_id', 1);
            });
})->find(1);

This is how the relationships are setup:

In Project.php

public function tasks()
{
    return $this->hasMany(Task::class, 'project_id')->setEagerLoads([]);
}

In Task.php

public function tags()
{
        return $this->morphToMany(Tag::class, 'taggable')->setEagerLoads([]);

}

Note that relationship between Task and Tags is of morphToMany.

Any pointers?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire