1

我试图在 cakephp 中复制以下查询:

SELECT *
FROM uploads, proposals
WHERE proposals.id = uploads.proposal_id AND proposals.tender_id = 10

我在 Upload 模型中使用 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' 

如您所见,提案表丢失了,有人可以解释一下如何进行此查询吗?

谢谢 :)

4

3 回答 3

1

我建议您为此使用可链接行为。它比 CakePHP 中默认的连接方式要容易得多。它适用于最新版本的 CakePHP 以及 1.3。

CakePHP 可链接行为

然后你会修改你的 find 看起来像这样:

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'
                ),
        ),
于 2012-10-18T15:23:52.350 回答
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 的直接翻译。如果您的模型正确相关,那么这一切都应该自动发生。

于 2012-10-18T15:16:09.217 回答
0

'contain'如果模型有关联,CakePHP 会自动按关键字加入表格。试试下面的代码:

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...

于 2012-10-18T15:45:42.680 回答