php - Laravel 5.5 Eloquent groupBy on ManyToMany Relationship

482

For example, I need taketags name and its not duplicate eachcategories

here mymodel

Post.php

class Posts extends Model
{
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    public function tags() : belongsToMany
    {
    return $this->belongsToMany(Tag::class, 'post_tag', 'post_id', 'tag_id');
    }
}

Category.php

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

Tag.php

class Tag extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

and here what I do.

Category::with(['posts.tags' => function($query){
        $query->groupBy('name'); // i need show tags name and group it, so its will not duplcate
    }])->get();

for$query->groupBy('name'); name istags name.

example

Categpry A
|__Title A
   |__Tag A
   |__Tag B
   |__Tag C
   |__Tag D
|__Title B
   |__Tag A
   |__Tag D
   |__Tag E

the result must beTag A, Tag B, Tag C, Tag D, Tag E i don't have an idea how to right now, any have a solution?...

thank you!

People are also looking for solutions to the problem: PHP performance: accelerators and HTTP servers

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.