I'm building a application that contains information about trees. Trees has belongs to many zones. So for solution I make two datatables called Trees and TreeZones they has primary and foreign keys thats match. I used "hasMany" and "belongsTo" operators to make a relationship between these two. Everythings works fine actually but there is one problem. The application has REST API controllers. In index function I'm pulling all tree data. And I need zones too. I solved this like this;
/**
public function index()
{
$trees = Tree::all();
foreach($trees as $key => $tree){
$treeData = Tree::find($tree->id);
foreach($treeData->zones as $zone)
{
$trees[$key]['zones'];
}
}
return ['data'=>$trees];
}
Output is like this;
{
"id": 1,
"name": "Kavak Ağacı",
"min": "-45.6",
"max": "-42.8",
"url": "https://p4.wallpaperbetter.com/wallpaper/255/713/198/poplar-trees-near-lake-wallpaper-preview.jpg",
"zones": [
{
"zone": "2a"
},
{
"zone": "4b"
}
]
},
.
.
.
}
But I want it to looks like this.
{
"id": 1,
"name": "Kavak Ağacı",
"min": "-45.6",
"max": "-42.8",
"url": "https://p4.wallpaperbetter.com/wallpaper/255/713/198/poplar-trees-near-lake-wallpaper-preview.jpg",
"zones": [
"2a",
"4b",
"5c"
]
},
.
.
.
}
How can I solve this with clean solutions?
CodePudding user response:
You can user transform()
method and use Eager loading rather than using DB call inside foreach loop.
Try this
public function index()
{
$trees = Tree::with(['zones'])->get();
$trees->transform(function($tree, $key) {
foreach ($tree->zones as $zoneKey => $zone) {
$trees["zones"][$zoneKey] = $zone->name //if you have name column
}
return $trees;
})
return ['data'=>$trees];
}