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

kvithalani's avatar

Group data in foreach loop which has same id

I have three tables products , product_attributes and product_attribute_values.

 products table has: Id, name, description, image, etc...
product_attributes table has: id, name, etc...
product_attribute_values has: id, product_id, attribute_id, value, etc..

Now, when I pass the product id to url I want product attributes in group. Like I have one product MOBILE which has attribute COLOR and it has three values BLACK, WHITE and GOLD. So, I want to group it by attribute. Can anyone helps me? How can I do it? in query I will get the result or I need to do it with loop? Thanks in advance!!!

0 likes
1 reply
jlrdw's avatar

Usually a group by is used with join, and the results is looped over to display the results.

An example

 $sql = "select distinct `account_types`.`AccountType` AS
`AccountType`,`accounts`.`AccountNumber` AS 
`AccountNumber`,`accounts`.`AccountName` AS `AccountName`,sum(`transactions`.`Expense`) AS `Sum_Expense`,sum(`transactions`.`Income`) AS `Sum_Income` from ((`account_types` join `accounts` on((`account_types`.`AccountTypeID` = `accounts`.`AccountTypeID`))) join `transactions` on((`accounts`.`AccountID` = `transactions`.`AccountID`))) where (`transactions`.`TransactionDate` Between '$bsdate' and  '$esdate') group by `account_types`.`AccountType`,`accounts`.`AccountNumber`,
`accounts`.`AccountName`";

Which when looped over produces:

A group by to me is mainly for reports like I've showed.

For a more complex query I don't use eloquent, I use getPdo()

Group data in foreach loop which has same id

I imagine you mean children, as parent would have a unique id.

That is what a group by is for. But you can use eloquent to eager load such data. To me a regular query is so much easier.

Eager loading flops on large data sets.

an example

first company
------- first company accounts payable list // only 5 here 

second company
------- second company accounts payable list // thousands 

etc

Eloquent is good for some things, but it's not for everything.

Don't try to paginate a group by, use group by when reports are needed.

Please or to participate in this conversation.