ORM:相关项目列表

时间:2018-08-29 06:25:57

标签: php lithium

我试图使用ORM查找省份及其城市列表。

结果与该列表相同:

"provinces": [
    {
        "name": "Prov.1",
        "Cities": {
            "name": "City.1"
        }
    },
    {
        "name": "Prov.1",
        "Cities": {
            "name": "City.2"
        }
    },
]

期望的是:

"provinces": [
    {
        "name": "Prov.1",
        "Cities": [
            {
                "name": "City.1"
            },
            {
                "name": "City.2"
            }
        ]
    },
]

使用的ORM:

Provinces::find('all', [
    'with' => ['Cities']
]);

1 个答案:

答案 0 :(得分:1)

类似

$array = [];
foreach($provinces as $province){
    $key = $province['name'];
    if(!isset($array[$key])){
       $array[$key] = [
         'name' => $province['name'], 
         'Cities' => [
              [ 'name' => $province['Cities']['name']];
          ]
       ];
    }else{
       $array[$key]['Cities'][] = ['name' => $province['Cities']['name']];
    }
}

 //strip keys
$array = array_values($array);

因为您没有发布实际的PHP数组,所以我只是猜测应该是什么。