Cakephp连接查询属于

Cakephp连接查询属于,php,mysql,cakephp,Php,Mysql,Cakephp,你好,我的数据库中有三个表国家、州和城市。在状态表中有一个国家id作为外键,在城市表中有状态id作为外键。问题是,当我在city表中查询时,我想获取国家名称。我将分享代码,以便您完全理解 Country.php class Country extends AppModel{ public $useTable = 'countries'; } class City extends AppModel{ public $useTable = 'cities'; p

你好,我的数据库中有三个表国家城市。在状态表中有一个
国家id
作为
外键
,在城市表中有
状态id
作为
外键
。问题是,当我在city表中查询时,我想获取国家名称。我将分享代码,以便您完全理解

Country.php

class Country extends AppModel{


    public $useTable = 'countries';
 }
class City extends AppModel{


    public $useTable = 'cities';

    public $belongsTo = array(
        'State' => array(
            'className' => 'State',
            'foreignKey' => 'state_id',
            'fields' => array('state.id','state.name')

        )
    );

  }
State.php

class Country extends AppModel{


    public $useTable = 'countries';
 }
class City extends AppModel{


    public $useTable = 'cities';

    public $belongsTo = array(
        'State' => array(
            'className' => 'State',
            'foreignKey' => 'state_id',
            'fields' => array('state.id','state.name')

        )
    );

  }
城市

好的,这是密码。如果我使用这个查询

$this->State->find('all', array(
            'conditions' => array(
                'state.country_id' => $country_id
            ),
我可以从国家表中获取国家名称。如果我在city表中这样做,情况也是如此

$this->City->find('all', array(
                'conditions' => array(
                    'city.state_id' => $state_id
                ),

我可以在这里找到所有的州名和城市名。因此,现在在同一个表中的一个查询中,我如何获得国家名称?

尝试使用
递归属性

设置
$this->City->recursive=2
获取表的关联数据和关联表上的关联数据

$this->City->recursive = 2;
$this->City->find('all', array(
            'conditions' => array(
                'city.state_id' => $state_id
            ),
            //other stuff you use in this find
));
您还可以使用“连接”标志


请参阅:

除了第一个答案之外,请确保包含
国家的外键

class City extends AppModel{

    public $belongsTo = array(
        'State' => array(
            'className' => 'State',
            'foreignKey' => 'state_id',
            'fields' => array('State.id','State.name', 'State.country_id'), // Make sure to contain the foreign key for the `Country`.
        )
    );
}
关于您的信息,您还可以使用
ContainableBehavior
而不是
recursive


谢谢您的回答。我试过这个。它成功地返回了州和城市的数据,但没有返回国家的数据。。。国家/地区数组为空。。请参阅[Country]=>Array()))是否已启用调试?如果是,您能检查一下它是否在SQL日志的查询中加入country表吗?我缺少什么?为什么它不加入我们还不确定。这是在运行find之前将recursive设置为2?我可以用一个硬连接更新我的答案,这个硬连接忽略了模型关联,如果你正在寻找一个快速而肮脏的修复方法的话。嗯,好的,现在一切都可以了。。顺便说一句,这是我的代码。检查它可能b我在这里做得不对返回$this->find('all',array('conditions'=>array('city.name LIKE'=>$query.%'),'recursive'=>2));