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

leinad95's avatar

Collection operations

Hello! Can you please help me with the following situation.

I have a collection of orders. I also have a "hasMany" relationship with an items table that contains basically the lines of the order (products). I want to find out how many pieces of each product I need in order to satisfy the necessity of those orders.

What can't be seen in the item collection is a product_id field and also the product_quantity filed.

Practically, out of this I would like to get the total number of products I need, in order for all of those orders to be fulfilled.

Collection {#488 ▼ #items: array:23 [▼ 0 => Order {#417 ▶} 1 => Order {#418 ▼ #table: "bdm_orders" #primaryKey: "order_id" +timestamps: false #connection: null #keyType: "int" #perPage: 15 +incrementing: true #attributes: array:23 [▶] #original: array:23 [▶] #relations: array:1 [▼ "items" => Collection {#416 ▼ #items: array:2 [▼ 0 => OrderItem {#490 ▼ #table: "bdm_order_item" #primaryKey: "order_item_id" +timestamps: false #connection: null #keyType: "int" #perPage: 15 +incrementing: true #attributes: array:7 [ …7] #original: array:7 [ …7] #relations: [] #hidden: [] #visible: [] #appends: [] #fillable: [] #guarded: array:1 [ …1] #dates: [] #dateFormat: null #casts: [] #touches: [] #observables: [] #with: [] #morphClass: null +exists: true +wasRecentlyCreated: false } 1 => OrderItem {#491 ▶} ] } ] #hidden: [] #visible: [] #appends: [] #fillable: [] #guarded: array:1 [▶] #dates: [] #dateFormat: null #casts: [] #touches: [] #observables: [] #with: [] #morphClass: null +exists: true +wasRecentlyCreated: false } 2 => Order {#419 ▶} 3 => Order {#420 ▶} 4 => Order {#421 ▶} 5 => Order {#422 ▶} 6 => Order {#423 ▶} 7 => Order {#424 ▶} 8 => Order {#425 ▶} 9 => Order {#426 ▶} 10 => Order {#427 ▶} 11 => Order {#428 ▶} 12 => Order {#429 ▶} 13 => Order {#430 ▶} 14 => Order {#431 ▶} 15 => Order {#432 ▶} 16 => Order {#433 ▶} 17 => Order {#434 ▶} 18 => Order {#435 ▶} 19 => Order {#436 ▶} 20 => Order {#437 ▶} 21 => Order {#438 ▶} 22 => Order {#439 ▶} ] }

Thank you!

0 likes
2 replies
martinbean's avatar

@leinad95 I don’t really understand the question, and the “debug” output doesn’t really help as it’s not formatted nor expandable.

Nevertheless, take a look at the available methods for collections. If you’re wanting to pull “nested” records, then sounds like you’re looking for something like pluck or flatMap.

leinad95's avatar

Ups! Sorry for the output of that being so unformatted. I will get back with a more precise output.

Thanks for the answer. :)

Please or to participate in this conversation.