Home > Net >  Many to Many Get All Distinct Values From a Related Model
Many to Many Get All Distinct Values From a Related Model

Time:06-20

I have an Article model with many-to-many relation with the Tag model

The Article model

class Article extends Model
{
    public function tags()
    {
        return $this->belongsToMany(Tag::class);
    }
}

The Tag model

class Tag extends Model
{
    public function articles()
    {
        return $this->belongsToMany(Article::class);
    }
}

What I want is to get all the unique tags that have a relation with at least one (or more) article in the articles table. I want to retrieve it through a static method in the Article model like below

public static function allTags()
{
   // return static:: all the tags
}

How can I do this? Thanks in advance.

EDIT: this is how I solved it. Appreciate the help!

public static function allTags()
{
        return Tag::query()->whereHas('articles', function($query) {
            $query->where('status', '<>', 'draft');
        })->pluck('tag', 'id');
}

CodePudding user response:

Using whereHas()

$tags = Tag::query()->whereHas('articles')->get();
  • Related