Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Mamad_Ch's avatar

Get pivot table data with query builder

Hello friends, is it possible to get the pivot table data with the help of Query Builder?

    $discusses = DB::table('discusses')
            ->join('discuss_tag','discusses.id','=','discuss_tag.discuss_id')
            ->join('tags','tags.id','=','discuss_tag.tag_id')
            ->where('parent_id',0)
            ->orderBy('discusses.id','desc')
            ->get();
Illuminate\Support\Collection {#1512 ▼
  #items: array:4 [▼
    0 => {#1519 ▼
      +"id": 20
      +"title": "Laborum est saepe q"
      +"content": "Laboris quae eveniet"
      +"parent_id": 0
      +"is_answer": 0
      +"vote": 0
      +"category_id": 2
      +"user_id": 22
      +"deleted_at": null
      +"created_at": "2021-09-25 18:08:15"
      +"updated_at": "2021-09-25 18:08:15"
      +"discuss_id": 2
      +"tag_id": 20
      +"name": ""
    }
    1 => {#1514 ▶}
    2 => {#1515 ▶}
    3 => {#1513 ▶}
  ]
}

As you can see, it does not return tag names .

I know you can use elequent, but I want to know if it can be used as a query builder? And how?

0 likes
3 replies
frankielee's avatar

so the data returned only including the discusses table's columns?

Try adding this before get()

->select('discusses.*', 'discuss_tag.*', 'tags.*')

If there are columns have the same name, the value will be replaced.

Btw, we didn't know your tables' structure and columns, also I don't know what you really want. I just can give the suggestion.

Mamad_Ch's avatar

@frankielee Thanks for your replay bro .

Let me explain better, I want to get data from the pivot table

pivot table => discuss_tag and columns discuss_id , tag_id

And naturally I have two tables called discusses and tags

I want a query so I can get tags for every discussion, only with Query Builder

frankielee's avatar

@Mamad_Ch

As you can see, it does not return tag names .

This is the name column? This column is under the pivot table?

  +"tag_id": 20
      +"name": ""

Is there any table's column has the duplicated name?

Please or to participate in this conversation.