我试图在cakephp中复制以下查询:
SELECT *
FROM uploads, proposals
WHERE proposals.id = uploads.proposal_id AND proposals.tender_id = 10
我使用上传模型中的find方法,条件如下:
$conditions = array(
'Proposal.id' => $id,
'AND' => array(
'Upload.proposal_id' => 'Proposal.id'
)
);
return($this->find('list', array('conditions' => $conditions)));
但我正在改变此查询
SELECT `Upload`.`id`, `Upload`.`title`
FROM `kumalabs_lic`.`uploads` AS `Upload`
WHERE `Proposal`.`id` = 10 AND `Upload`.`proposal_id` = 'Proposal.id'
如您所见,提案表缺失,有人可以解释我如何进行此查询?
谢谢:)
答案 0 :(得分:1)
我建议您使用此链接行为。它比在CakePHP中进行连接的默认方式容易得多。它适用于最新版本的CakePHP,以及1.3。
然后,您可以修改您的查找,如下所示:
return($this->find('list', array(
'link' => array('Proposal'),
'conditions' => array(
'Proposal.id' => $id,
),
'fields' => array(
'Upload.*',
'Proposal.*',
),
)));
CakePHP将自动加入您的主键/外键,因此无需使用
'Upload.proposal_id' => 'Proposal.id'
条件。
虽然你不需要这种条件,但我也想指出你做错了。这就是你在CakePHP中做AND和OR的方法
'conditions' => array(
'and' => array(
'field1' => 'value1', // Both of these conditions must be true
'field2' => 'value2'
),
'or' => array(
'field1' => 'value1', // One of these conditions must be true
'field2' => 'value2'
),
),
答案 1 :(得分:0)
我不熟悉JOIN语法,但我相信它等于:
SELECT *
FROM uploads
INNER JOIN proposals ON proposals.id = uploads.proposal_id
WHERE proposals.tender_id = 10
...所以你需要类似的东西:
// Untested
$conditions = array(
'Proposal.id' => $id,
'joins' => array(
array(
'alias' => 'Proposal',
'table' => 'proposals',
'type' => 'INNER',
'conditions' => 'Proposal.id = Upload.proposal_id',
),
),
);
当然,这是您JOIN的直接翻译。如果您的模型正确相关,则应该自动完成。
答案 2 :(得分:0)
如果模型有关联,CakePHP会自动通过'contain'
关键字加入表格。试试下面的代码:
public function getProposalsFromTender($id){
$data = $this->find('all', array(
'conditions' => array('Proposal.id' => $id),
'fields' => array('Upload.*', 'Proposal.*'),
'contain' => array('Proposal')
));
return($data);
}
注意:
CakePHP使用显式连接而不是像...from proposals, uploads...