How to assign id as parent to next row column as child

  laravel, php

I’m developing an e-commerce for user to select multiple product. In addition, user are able to select same product as a bundle with different quantity, description and prices as child.

user data input

index  product qty
1      200     2   
2      200     1   
3      201     2 
4      201     1

Sale_item table

ID    - ProductID - ParentID - type.   - qty
1001  - 200       - null     - bundle  - 2
1002  - 200       - null     - bundle  - 1
1003  - 201       - 1001     - child   - 2
1004  - 201       - 1002     - child   - 1

How could I assign the parent id for the child when user select a same product? I have no idea how to identity which parent should assign to which child since their are the same product id.

What i have tried

$bundle = Sale_item::select('id', 'item_id')
                                ->where('type', 'bundle')
                                ->get();

            if ($bundle) {
                $child = Sale_item::find($model->id);
                foreach ($bundle as $parent) {
                    if ($parent->item_id === $model->parent_item_id) {
                        $child->parent_id = $parent->id;
                        $child->save();
                    }
                }
            };  

The code above will update all the child with first parent id only. the parent id 1002 for second child is gone.

Sale_item table

ID    - ProductID - ParentID - type.   - qty
1001  - 200       - null     - bundle  - 2
1002  - 200       - null     - bundle  - 1
1003  - 201       - 1001     - child   - 2
1004  - 201       - 1001     - child   - 1
 

Source: Laravel

Leave a Reply