Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Leff7's avatar
Level 4

Constraining relationship query by an array

I have 3 models Content, ContentType, and Taxonomy. Their relationships are set up like this:

Content model:

public function contentType()
{
    return $this->belongsTo('App\ContentType', 'ct_id');
}
public function taxonomies()
{
    return $this->morphToMany('App\Taxonomy', 'taxonomical');
}

ContentType model:

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

Taxonomy:

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

I am getting an array with taxonomies that I should use to filter the contents, the array could look like this one:

$taxonomiesArray =  ["Administrasjon", "Oslo", "Bane"]

With this kind of array I should make a query, where I would get only contents, that have all the taxonomies from that array, and are of contentType where column name is intranet-post, basically something like this:

$intranetTypePostID = ContentType::where('name', 'intranet-post')->pluck('id');
$contents = Content::where('ct_id', $intranetTypePostID)->with('taxonomies')->get();

But, how can I get only contents that have all the taxonomies that have the same name as the values from the array $taxonomiesArray?

0 likes
1 reply
ftrillo's avatar

Do you want the contents that are related to ALL of the taxonomies in the array? Or the contents that are related to ANY of the taxonomies in the array?

Also, where are you getting the names from? Because It would be easier to do if instead of getting an array of names you got an array of primary keys(aka id).

Please or to participate in this conversation.