Laravel - querying polymorphic relationship

2019-07-31 16:41发布

I have tables content, taxonomies, content_taxonomies and content_types. Their relationships are set up like this:

Content model:

public function taxonomies()
{
    return $this->morphMany('App\ContentTaxonomy', 'taxonomical');
}

Taxonomy model:

public function content()
{
    return $this->hasManyThrough('App\Content', 'App\ContentTaxonomy');
}

ContentTaxonomy model:

public function content()
{
    return $this->morphedByMany('App\Content', 'taxonomical');
}

public function term()
{
    return $this->hasOne('App\Taxonomy', 'id', 'taxonomy_id');
}

ContentType model:

public function contents()
{
    return $this->hasMany('App\Content', 'ct_id');
}

taxonomies table has this columns with a record example:

id | tt_id |    slug    |     name
       1     prevensjon    Prevensjon

content_taxonomies has columns with a record example:

id | taxonomy_id | taxonomical_id | taxonomical_type
           1             1               App\Content

content_types has columns with a record example:

id | name | slug
     post   post

I have a route with 2 optional arguments, for example prevensjon/prosjektsamarbeidets-verdi where the first argument is taxonomy slug, and the second argument is the slug of the content. I need to make the query, where I would have to find the content that has the content_type with the slug post or page and that also belongs to taxonomy with the slug of prevensjon and that has itself the same slug as prosjektsamarbeidets-verdi. So far I am fetching content that has the content type where the slug is equal to post and where the content slug is equal to the slug that I am sending which is in this case prosjektsamarbeidets-verdi.

$content = Content::whereHas('contentType', function ($query) {
                      $query->where('slug', 'post');
                    })
                    ->where('slug', $arguments['slug'])
                    ->with('supplementary')
                    ->first();

But, not sure how to do expand this query so that I can check further if the content has the taxonomy with the same slug that I am sending as an argument which is in this case prevensjon?

0条回答
登录 后发表回答