Skip to content
Advertisement

Get data from same table with child rows in same collection using laravel

I have a table with multiple rows, which contain parent and child rows, in case I need to get data to the same collection. This means getting child row data inside the parent row using laravel.

id type price is_substitute subsitute_parent
1 Type A 12 0 null
2 Type B 44 1 1
3 Type C 23 1 1
4 Type D 11 0 null
5 Type E 45 1 4
6 Type F 25 1 4

“subsitute_parent” id means the parent row id of this table. How can I do this using laravel.

I tried using get all data from the table and the add collection to foreach and then create parent row array and child row array, but this method is not efficient.

$returnedData = ItemModel::all();
$structPODetails = [];

foreach ($returnedData as  $tableRow) {
    if (!empty($tableRow->subsitute_parent)) {
       $structPODetails['child_items'][] = $tableRow;
    } else {
       $structPODetails['parent_items'][] = $tableRow;
    }
}

return $structPODetails;

Advertisement

Answer

As I understood

In ItemModel.php

class ItemModel extends Model
{
    public function parent()
    {
        return $this->belongsTo(ItemModel::class, 'subsitute_parent');
    }

    public function children()
    {
        return $this->hasMany(ItemModel::class, 'subsitute_parent');
    }
}

Then in the controller, add.

$structPODetails = ItemModel::with('children')->get();

This will give you output as

[
    {
        "id": 1,
        ...
        "children": [
            {
                "id": 2,
                ..
            },
            {
                "id": 3,
                ...
            }
        ]
    },
    {
        "id": 4,
        ...
        "children": [
            {
                "id": 5,
                ...
            },
            {
                "id": 6,
                ..
            }
        ]
    }
]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement