I'm building an application that contains information about trees. Trees belong to many zones. So to solve this problem, I created two data tables called Trees and TreeZones, which have matching primary keys and foreign keys. I used the "hasMany" and "belongsTo" operators to establish the relationship between the two. Everything actually works fine, but there's a problem. The application has REST API controller. In the index function I am getting all the tree data. I also need zones. I solved the problem 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'][] = $zone->zone;
}
}
return ['data'=>$trees];
}
The output results are as follows:
{
"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 the result to look 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 to solve this problem with a concise solution?
You can use the
transform()method and use eager loading instead of using DB calls in a foreach loop. Try thispublic function index() { $trees = Tree::with(['zones'])->get(); $trees->transform(function($tree, $key) { foreach ($tree->zones as $zoneKey => $zone) { $trees["zones"][$zoneKey] = $zone->name //如果你有name列 } return $trees; }) return ['data'=>$trees]; }