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

Zeesab's avatar
Level 12

DB Query Builder to Resource

Hi Guys,

Sorry if this sound dumb but I have not used DB query builder extensively and used eloquent most of the time.

I have this requirement where I want to use query builder along with several joins etc.

so my query looks like this so far

  [
  {
     "user_id": 20,
     "first_name": "Zeeshan",
     "last_name": "Sabri",
     "email": "[email protected]",
     "phone": null,
     "id": 1,
     "model_type": "test",
     "model_id": 20,
  },
 {
     "user_id": 20,
     "first_name": "Zeeshan",
     "last_name": "Sabri",
     "email": "[email protected]",
     "phone": null,
     "id": 2,
     "model_type": "test,
     "model_id": 20,
  },
]

But what I do what is this

[
  {
     "user_id": 20,
     "first_name": "Zeeshan",
     "last_name": "Sabri",
     "email": "[email protected]",
     "phone": null,
     "models": {
      "id": 1,
       "model_type": "test",
        "model_id": 20,
       },
       {
       "id": 2,
       "model_type": "test2",
        "model_id": 20,
       },
]

I understand I can get to that using loop but before I do that I want to check with you geniuses here that is there a proper way of doing this?

0 likes
2 replies
Sinnbeck's avatar

That is what relationships are for :) I assume those two fields are in another table, so you load it as a relationship, and use nested resources.

Zeesab's avatar
Level 12

@Sinnbeck but I'm using Query builder and can't using ->with can I?

Yes they are in different table. That's why I had to use join. Also I simplified the question in reality I have to use a lot join to get the information I want that's why using query builder.

Please or to participate in this conversation.