0

I have 3 tables, first is users, post_tag, posts. The posts table has user_id column.

I tried groupBy in model relationship, but it doesn't work, it's still giving me duplicate result (see my code below). Someone knows how to get unique tag_id?


Here is my User model

public function post_tags()
{
    return $this->hasManyThrough(PostTag::class, Post::class)
        ->groupBy(['post_id','tag_id','user_id']);
}

I test it using below code, but still giving me duplicate tag_id data.

\App\Models\User::find(11)->post_tags

I already been to these links, I did the same thing but none works for me. Laravel Grouping by Eloquent Relationship, Laravel group by, with relationship in different tables

  • Why don't you do it with simple DB query than relationship? 1 direct query to take all unique tag_id would be a lot faster, after that you can load them with their Model.. – Svetoslav Oct 30 '20 at 08:11
  • @Svetoslav I once ask yesterday related to this question, there some user told me to do Eloquent way to be more convenient and faster. And now your recommending me to do db query again, I'm confused. which is really best. – アリ・ナディム Oct 30 '20 at 08:33
  • When it is build as relationship on select you are trying to fetch everything at once usually with more complicated queries. It is more comfortable if it is define as some kind of relationship or scope inside a Eloquent model as you can use it as much as you want with no more query code at the backend. With 1 simple DB query for fetching the tag_ids and if you need the object 2nd eloquent select of the Tags by those ids, is the fastest approach from Sql side. In case you don't plan to make such selection on many pages and etc it is a good solution. – Svetoslav Oct 30 '20 at 08:48

0 Answers0