如何从cakephp 3中的两个表中获取数据

时间:2017-10-04 06:09:59

标签: mysql cakephp cakephp-3.0

我是cakephp的新手,我的桌子就像:

city
id | name
1  | city1
2  | city2

state
id | name | cityid
1  |state1| 2

所以,如果我有州身份证,我如何获得城市名称。  在控制器中我有这样的代码。

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

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

在$ sId中我获得了值,所以我该怎么写查询。

1 个答案:

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