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;
3
Answers
use laravel Eloquent way.
In the model add relationship has many
and in your controller
Model Logic
controller logic
As I understood
In
ItemModel.php
Then in the controller, add.
This will give you output as