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!