2016-03-25 24 views
1

,Yii2 dönüş JSON biçimi aşağıda bu veriler almaya çalışıyorum

Tablo ilişkileri:

kişi (bir) < ---> (birçok) people_info (bir) < ---> (birçok) aşağıdaki biçimde

ile şu

people: { 
    p_id: 10, 
    p_price: 3.99, 
    people_info : [ 
     { 
      pl_id: 3, 
      pl_state: 2, 
      pl_district: 6, 
      pl_latitude: 6.323434, 
      pl_longitude: 108.23499, 
      people_contact: [ 
       { 
        plc_id: 2 
       }, 
       { 
        plc_id: 1 
       } 
      ] 
     }, 
     { 
      pl_id: 2, 
      pl_state: 7, 
      pl_district: 12, 
      pl_latitude: 6.000434, 
      pl_longitude: 108.9910003, 
      people_contact: [ 
       { 
        plc_id: 5 
       }, 
       { 
        plc_id: 9 
       } 
      ] 
     } 
    ] 
} 

people_contact se kontrolör kodları,

class PeopleController extends Controller 
{ 
public function actionPeople($params){ 
    Yii::$app->response->format = Response::FORMAT_JSON; 

....//some other codes//.....  
     $people= People::find()->select(['p_id', 'p_price'])->where(['p_id' => $itemId])->one(); 
     $info= PeopleContact::find()->with(['plPeople'])->asArray([])->all(); 

    return array(
     'people' => $people, 
     'info' => $info, 
    ); 
} 

} 

Ben bunları aldım

,

"people": { 
    "p_id": "3", 
    "p_price": "32.42" 
}, "locations": [{ 
    "pl_id": "1", 
    "pl_people": "3", 
    "pl_title": "", 
    "pl_latitude": "6.16438700000000000000", 
    "pl_longitude": "102.28314649999993000000", 
    "pl_place": null, 
    "pl_premise": null, 
    "pl_street": "1", 
    "pl_area": "1", 
    "pl_postcode": "1", 
    "pl_district": "1", 
    "pl_state": "3", 
    "pl_country": 1, 
    "place": null, 
    "premise": null, 
    "street": null, 
    "area": null, 
    "postcode": null, 
    "district": null, 
    "state": null, 
    "country": "United Kingdom", 
    "contacts": [{ 
     "plc_name": "joe", 
     "plc_phone": "123456", 
     "plc_email": null 
    }] 
}] 
} 

nasıl üst kısmında belirtilen formatta bunu başarmak mı?

cevap

1
$output; 

$people=People::find()->select(['p_id', 'p_price'])->asArray()->all(); 
foreach($people as $person) { 
    $infos = PersonInfo::find()->where(['person_id' => $person->id])->asArray()->all(); 
    foreach($infos as $info) { 
     $contacts = PersonContact::find()->where(['person_info_id' => $info->id])->asArray()->all(); 
     foreach($contacts as $contact) { 
      $info['contacts'][] = $contact; 
     } 
     $person['info'][] = $info 
    } 
    $output['people'][] = $person 
} 

return $output; 

Sen döngü aracılığıyla gerektiği ve bu getirme gibi veriler: insanlar> bilgi> öncekinden getirilen bilgi güvenerek her üst seviyeye başvurun. Ardından, yukarıda gösterildiği gibi istediğiniz biçimde saklayın.

benzeri çıktısı verir şey:

"people": [{ 
    ... 
    "info": [{ 
     ... 
     "contacts": [{ 
      ... 
     },{ 
      ... 
     }] 
    }] 
},{ 
    ... 
}] 
İlgili konular