Cakephp加入查询属于

时间:2016-02-22 16:34:46

标签: php mysql cakephp

你好,我的数据库中有三个表。 国家/地区城市。在状态表中,country_idforeign key,城市表中state_idforeign key。问题是当我在城市表中查询时,我想获得国家名称。我将分享代码,以便您完全理解

Country.php

class Country extends AppModel{


    public $useTable = 'countries';
 }

State.php

class City extends AppModel{


    public $useTable = 'cities';

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

        )
    );

  }

城市

class State extends AppModel{


    public $useTable = 'states';

    public $belongsTo = array(
        'Country' => array(
            'className' => 'Country',
            'foreignKey' => 'country_id',
            'fields' => array('Country.id','Country.name','Country.short_name')

        )
    );

好的,这是代码。如果我使用此查询

$this->State->find('all', array(
            'conditions' => array(
                'state.country_id' => $country_id
            ),

我可以从国家/地区表中获取国家/地区名称。情况也一样如果我在这样的城市表中这样做

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

我可以在这里获取所有州名城市名称。那么现在在一个查询的同一个表中我如何获得国家名称?

2 个答案:

答案 0 :(得分:0)

尝试使用recursive属性。

设置$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
));

您也可以使用“加入”标志。

$this->City->find('all', array(
    'conditions' => array(
        'City.state_id' => $state_id
    ),
    'joins' => array(
        array(
            'table' => 'states',
            'alias' => 'State',
            'type' => 'left',
            'conditions' => 'State.id = City.state_id'
        ),
        array(
            'table' => 'countries',
            'alias' => 'Country',
            'type' => 'left',
            'conditions' => 'Country.id = State.country_id'
        )
    ),
    'fields' => array('City.id', 'State.name', 'Country.name', 
         //include all the fields you need
    )
));

请参阅:http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive

答案 1 :(得分:0)

除第一个答案外,请确保包含Country的外键。

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

http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html