如何防止多对多 Laravel 查询中的重复数据

How to prevent duplicate data on many to many Laravel query

我的数据库中有三个表,只是为了举例说明,内容是这样的:

+----------------------------+
|      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      |
+-------------------+

使用 Eloquent-Laravel 查询表我需要这样的东西:

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

但是我正在使用的查询得到类似的结果。

[
  {
    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"
  }
]

我正在使用的查询:

$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)

除了联接之外,我还可以使用什么来将所有标签分组到一个字段中?

试试这个

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