Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Many to Many Get All Distinct Values From a Related Model

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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');
}

>Solution :

Using whereHas()

$tags = Tag::query()->whereHas('articles')->get();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading