我是CakePHP的新手,我正在阅读手册并买了这本书,我遇到了一个问题,需要一些帮助。
目前我这样查询我的数据库(这是全班):
<?php
class TapplicantController extends AppController {
public function index() {
$this->set('page_title', 'Dashboard');
$tapplicant = $this->Tapplicant->query("SELECT tapplicant.AppID, tapplicant.AppIPAddress, tapplicant.AppAffID, tapplicant.AppDate, tapplicant.FirstName, tapplicant.LastName, tapplicant.Email, tapplicant.AppDomain, toutcome.AffCommission FROM tapplicant INNER JOIN toutcome ON tapplicant.AppID=toutcome.AppID LIMIT 0,15 ");
$this->set('tapplicant', $tapplicant );
}
}
然后我像这样显示它并且工作正常:
<?php foreach ($tapplicant as $tapplicant) : ?>
<tr>
<td><?=$tapplicant['tapplicant']['AppID']; ?></td>
<td><?=$tapplicant['tapplicant']['AppAffID']; ?></td>
<td><?=$tapplicant['tapplicant']['FirstName']; ?></td>
<td><?=$tapplicant['tapplicant']['LastName']; ?></td>
<td><?=$tapplicant['tapplicant']['Email']; ?></td>
<td><?=$tapplicant['tapplicant']['AppDate']; ?></td>
<td><?=$tapplicant['tapplicant']['AppDomain']; ?></td>
<td><?=$tapplicant['tapplicant']['AffCommission']; ?></td>
</tr>
<?php endforeach; ?>
问题是我有Inner Joined 2表并且它不起作用,我收到以下错误:未定义的索引:AffCommission
答案 0 :(得分:1)
除非您真的无法使用Cake way编写查询,否则您不应该使用query()
来检索CakePHP中的数据。要在Cake中使用连接,您的查询应如下所示: -
$tapplicant = $this->Tapplicant->find(
'all',
array(
'fields' => array(
'Tapplicant.*',
'Toutcome.*'
),
'joins' => array(
array(
'table' => 'toutcome',
'alias' => 'Toutcome',
'type' => 'INNER',
'conditions' => array('Tapplicant.AppID = Toutcome.AppID')
)
),
'limit' => 15
)
);
然后,应该通过模型别名索引生成的数组,因此$tapplicant['tapplicant']['AffCommission'];
应该类似于$tapplicant['Toutcome']['AffCommission'];
。调试此方法的最简单方法是查看返回的数组是什么,因此在代码中使用print_r($tapplicant)
或debug($tapplicant)
来查看返回的内容。
只要您正确地关联模型,Containable behaviour可能会使它更简单。
你没有使用CakePHP naming conventions你真的应该这样做,否则你在使用Cake时会遇到很多困难。我建议您从一开始就阅读在线文档,然后再深入了解!
答案 1 :(得分:0)
Try:
$options['joins'] = array(
array(
'table' => 'toutcome',
'alias' => 'Toutcome',
'type' => 'INNER',
'conditions' => array('Tapplicant.AppID = Toutcome.AppID')
)
);
$options['fields'] = array(
Tapplicant.AppID,
Tapplicant.AppIPAddress,
Tapplicant.AppAffID,
Tapplicant.AppDate,
Tapplicant.FirstName,
Tapplicant.LastName,
Tapplicant.Email,
Tapplicant.AppDomain,
Toutcome.AffCommission
);
$options['limit'] = 15;
$tapplicant = $this->Tapplicant->find('all', $options);