我想查看联接中的所有记录,并在联接的每一侧设置WHERE条件。

例如,我有LOANBORROWER(已加入borrower.id = loan.borrower_id)。我想要LOAN.field = 123和BORROWER.field = 'abc'的记录。

这里的答案(例如this one)似乎表明我应该使用Containable。

我试过了这是我的代码:

$stuff = $this->Borrower->find('all', array(
    'conditions' => array(
        'Borrower.email LIKE' => $this->request->data['email'] // 'abc'
    ),
'contain'=>array(
    'Loan' => array(
        'conditions' => array('Loan.id' => $this->request->data['loanNumber']) // 123
        )
    )
));

我希望得到一个结果,因为在我的数据中,只有两个条件的联合记录。相反,我得到两个结果,

结果1是{Borrower: {field:abc, LOAN: {field: 123} } //正确

结果2是{Borrower: {field:abc, LOAN: {NULL} } //错误

当我查看CakePHP使用的SQL时,没有看到联接。我看到的是两个单独的查询:

查询1:SELECT * from BORROWER // (yielding 2 IDs)

查询2:SELECT * FROM LOAN WHERE borrower_id in (IDs)
这不是我想要的。我想加入表格,然后应用我的条件。我可以很容易地编写SQL查询,但是由于我们采用了该框架,因此我想尝试以Cake的方式进行。

可能吗?

最佳答案

尝试执行以下操作:

    $options['conditions'] = array(
           'Borrower.email LIKE' => $this->request->data['email'] // 'abc',
           'loan.field' => '123' )

    $options['joins'] = array(
        array('table' => 'loans',
              'alias' => 'loan',
              'type' => 'INNER',
              'conditions' => array(
                    'borrower.id = loan.borrower_id')
                )
            );

    $options['fields'] = array('borrower.email', 'loan.field');

    $test = $this->Borrower->find('all', $options);

您应该看到类似以下的SQL语句:
SELECT borrower.email, loan.field
FROM borrowers AS borrower
INNER JOIN loans AS loan
    ON borrower.id = loan.borrower_id
    AND loan.field = '123'
WHERE borrower.email = 'abc'

您的结果将在数组中
{Borrower: {field:abc} LOAN: {field: 123} }

您可以在document中找到更多信息。

10-07 14:17