你好,我的数据库中有三个表。 国家/地区、州和城市。在州表中有一个country_id
作为外键
,在城市表中有一个state_id
作为外键
。问题是我想在城市表中查询时获取国家/地区名称。我将分享代码以便您能够充分理解
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
),
我可以在这里获取所有州名城市名称。那么现在在同一个表中的一个查询中我如何才能获取国家/地区名称?
最佳答案
尝试使用递归
属性。
设置 $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
));
您还可以使用“joins”标志。
$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
关于php - Cakephp加入查询属于,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35558901/