我想查看来自联接的所有记录,在联接的每一侧设置WHERE
条件。
例如,我有LOAN
和BORROWER
(加入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方式执行它,因为我们已经采用了该框架。
有可能吗?
答案 0 :(得分:6)
尝试做这样的事情:
$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找到更多信息。
答案 1 :(得分:2)
我想我会接受何塞的回答,因为这正是我想要的。但我确实注意到我不需要任何花哨的技巧 - 没有连接或包含 - 如果我使用其他模型作为我的起点。
Borrower
hasMany
Loan
和Loan
belongsTo
一个Borrower
。使用Loan
作为我的模型,Cake会自动加入表格,但不会使用Borrower
。
$this->Loan->find('all', array( // Not $this->Borrower->find() !
'conditions' => array(
'Borrower.field' => 'abc',
'Loan.field' => 123
)
));