Search code examples
laravellaravel-query-builder

How to prevent duplicate data on many to many Laravel query


I have three tables in my DB and just to exemplify, the content is something like that:

+----------------------------+
|      Videos                |
+----------------------------+
| id | title        | source |
|  1 | Numerals     | 3      |
|  2 | Colonial Age | 3      |
| ...| ...          | ...    | <--- other videos with different source
+----------------------------+

+------------------------+
|        Video-Tags       |
+------------------------+
| id | video_id | tag_id |
|  1 |        1 |      1 |
|  2 |        1 |      2 |
|  3 |        1 |      3 |
|  4 |        2 |      2 |
|  5 |        2 |      3 |
+------------------------+

+-------------------+
|      Tags         |
+-------------------+
| id | title        |
|  1 | Alpha        |
|  2 | Bravo        |
|  3 | Charlie      |
+-------------------+

Querying tables using Eloquent-Laravel I need get something like that:

[
  {
    id:1,
    title: Numerals,
    tags: "Alpha, Bravo, Charlie"
  }
  {
    id:2,
    title: Colonial Age,
    tags: "Bravo, Charlie"
  }
]

But I getting something like this with the query I'm using.

[
  {
    id:1,
    title: Numerals,
    tags: "Alpha"
  },
  {
    id:1,
    title: Numerals,
    tags: "Bravo"
  },
  {
    id:1,
    title: Numerals,
    tags: "Charlie"
  },
  {
    id:2,
    title: Colonial Age,
    tags: "Bravo"
  },
{
    id:2,
    title: Colonial Age,
    tags: "Charlie"
  }
]

The query I'm using:

$videos = Videos::where('source', 3)
          ->join('video-tags', 'video-tags.video_id', 'video.id')
          ->join('tags', 'tags.id', 'video-tags.tag_id')
          ->select('videos.*', tags.title as tags)

What can I use besides a join to group all tags in a single field?


Solution

  • Try this

    $videos = Videos::where('source',3)->with('tags')->get();