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

danhorton's avatar

Creating collection wiith relationships (nesting) from 2 query builder queries

I'm trying to create a collection from 2 query builder results. These execute correctly and return as expected, i'm now just trying to transform them into how I need.

        $bid = collect(DB::connection('sqlsrv')->table('Bids')->select('*')->where('crm_ref', '=', $sn)->get());
        $crm = collect(DB::connection('sqlsrv_crm')->table('OpportunityBase')->select('*')->where('new_SalesNumber', '=', $sn)->get());
dd($result = $bid->merge($crm));

This returns a collection with 2 items:

Collection {#496 ▼
  #items: array:2 [▼
    0 => {#452 ▶}
    1 => {#498 ▶}
  ]
}

How I want is as below (i.e. with the $crm nested into $bid->crm as eloquent does):

Collection {#496 ▼
  #items: array:1 [▼
    0 => {#452 ▶}
                  1 => {#498 ▶}
  ]
}

I also tried $bid->push($crm) however this just creates a flat collection.

0 likes
0 replies

Please or to participate in this conversation.