"Laravel One-To-Many relationships require data to be in the Model::all() output"
P粉310754094
P粉310754094 2023-09-14 22:56:53
0
1
619

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?

P粉310754094
P粉310754094

reply all(1)
P粉662802882

You can use the transform() method and use eager loading instead of using DB calls in a 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 //如果你有name列
        }
        return $trees;
    })
    
   return ['data'=>$trees];
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!