2017-10-04 3 views
1

내가 CakePHP의 새로운 오전 내 테이블에 두 테이블에서 데이터를 가져 오기하는 방법 같은 :CakePHP의 3

city 
id | name 
1 | city1 
2 | city2 

state 
id | name | cityid 
1 |state1| 2 

그래서 난 상태 ID를 가진 경우 i는 도시 이름을 얻는 방법에 대해 설명합니다. 컨트롤러에이 코드가 있습니다.

public function getCity() 
    { 
     if($this->request->is('ajax')) { 
     $this->autoRender = false; 
    } 

    if ($this->request->isPost()) { 
     $sId= $this->request->data['stateid']; 
    } 
    } 

$ sId에서 값을 얻으려면 어떻게해야합니까? 이 두 모델 사이에 BelongsTo 관계가있는 경우

+2

https://book.cakephp.org/3.0/en/orm/associations.html 첫 번째 – tarikul05

+0

을 읽어야한다고 생각합니다. 도시와 주 모델 간의 연결을 수행 했습니까? –

+0

예, giveTo를 지정하십시오. –

답변

0

, 당신은 단지 포함 미국에 대한 쿼리를해야 할 도시 :

public function getCity() 
{ 
    if($this->request->is('ajax')) { 
     $this->autoRender = false; 
    } 

    if ($this->request->isPost()) { 
     $stateEntity = $this->States->find('all') 
      ->where(['id' => $this->request->data['stateid']]) 
      ->contain(['Cities']) 
      ->first(); 
     // Now the State Object contains City 
     $cityName = $stateEntity->city->name; 
    } 
} 

이 같이 할 필요가이 관계를 만들려면 :

class StatesTable extends Table 
{ 

    public function initialize(array $config) 
    { 
     $this->belongsTo('Cities') 
      ->setForeignKey('city_id') 
      ->setJoinType('INNER'); 
    } 
}