如何从 cakephp 3 中的两个表中获取数据
How to Fetch data from two tables in cakephp 3
我是 cakephp 的新手,我的 table 喜欢:
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 中我得到了值,所以我该如何编写查询。
如果两个模型之间有 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');
}
}
我是 cakephp 的新手,我的 table 喜欢:
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 中我得到了值,所以我该如何编写查询。
如果两个模型之间有 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');
}
}