Mark Kendall
Mark Kendall

Reputation: 129

Laravel 4.2 Eloquent query by relationship column value

Good day to you all...

I'm trying to access a collection based on a column in a related table within Eloquent (Laravel 4.2).

I have the following tables:

tags:

(int) id
(string) name

tag_usage:

(int) id
(string) model (the name of the model that is allowed to use the tag)

tag_tag_usage: (pivot)

(int) id
(int) tag_id
(int) tag_usage_id

I also have a taggables (polymorphic to store tags for multiple models) table which I believe is out of scope here as I only want to retrieve the tags that am allowed to use for each model.

My tag model has the relationship

public function usage()
{
    return $this->belongsToMany('TagUsage');
}

and the TagUsage model has

public function tags() {
    return $this->belongsToMany('Tag');
}

Now, what I want to do is return the tags that ONLY have a specific usage, some pseudo code would be

get_tags->where(tag_usage.model = modelname)

which would return only a subset of the tags.

Tried a few things with no success so over to the many fine brains available here.

Many thanks.

Upvotes: 0

Views: 1145

Answers (1)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

You need to use whereHas in the following way:

$tags = Tag::whereHas('usage', function($q)
{
    $q->whereModel('modelname');

})->get();

Upvotes: 2

Related Questions