如何获取CakePHP中3

问题描述:

我在新的CakePHP和我的表从两个表中的数据,如:如何获取CakePHP中3

city 
id | name 
1 | city1 
2 | city2 

state 
id | name | cityid 
1 |state1| 2 

那么,如何让城市的名字,如果我有状态ID。 在控制器中我有这样的代码。

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

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

在$ sId我得到的价值,所以我如何写查询。

+2

我认为你应该阅读https://book.cakephp.org/3.0/en/orm/associations.html第一个 – tarikul05

+0

你做过城市和州模型之间的任何关联吗? –

+0

是的,给它belongsTo –

如果你有两个型号之间的属于关联关系,你只要做对国家,其包含查询城市:

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'); 
    } 
}