1

I have two tables -

table collages - [id, name]

table products - [id, name, collage_id]

I want to get all the collages with the products who has related collage_id.

This is my code

 $collages = Collages::all();

  foreach($collages as $collage){
    $collage['products'] = Product::getByCollageId($collage['id']);
  }

And this is the output -

 Array
(
[id] => 12
[collage_name] => frida_calo.jpeg
[products] => Array
    (
        [0] => Array
            (
                [id] => 11
                [name] => couch
                [collage_id] => 12
            )

    )

 )

It seems that every iterate the next product remove the previous product. How can I get all the products in an array?

  • Actually, I think the way you're saving it sounds okay. Can you explain more about what you mean by "get all the collages with the products who has related collage_id"? Ideally include some example data and the output you're trying to achieve. – Don't Panic Aug 23 '17 at 17:14
  • @Don'tPanic Hey, added the question, thank you –  Aug 23 '17 at 17:18
  • Relational database management systems like MySQL deal in rectangular arrays of data. Each table, and each result set, contains a fixed number of columns of data, and is populated with zero or more rows. Each row has the same format and number of columns as the other rows. If you want some kind of hierarchical setup with an array of detail rows under each master row, you need to generate that in an application program. – O. Jones Aug 23 '17 at 17:29
  • After your edit, it looks like you're using some kind of framework. Most of them have built-in methods to get related data like this. – Don't Panic Aug 23 '17 at 17:53

1 Answers1

0

Change

foreach($collages as $collage)

To

foreach($collages as &$collage)

The reference operator -- =& -- will ensure that you're working with the actual $collage inside the foreach loop, not a copy of it that is lost once you move to the next loop iteration.

BeetleJuice
  • 39,516
  • 19
  • 105
  • 165