CakePHP查找每个表上带有条件的连接记录
我想查看连接中的所有记录,在连接的每一侧设置CakePHP查找每个表上带有条件的连接记录,cakephp,join,cakephp-2.0,Cakephp,Join,Cakephp 2.0,我想查看连接中的所有记录,在连接的每一侧设置WHERE条件 例如,我有贷款和借款人(加入日期为BORROWER.id=LOAN.BORROWER\u id)。我想要LOAN.field=123和BORROWER.field='abc'的记录 这里的答案(例如)似乎是说我应该使用Containable 我试过了。这是我的密码: $stuff = $this->Borrower->find('all', array( 'conditions' => array(
WHERE
条件
例如,我有贷款
和借款人
(加入日期为BORROWER.id=LOAN.BORROWER\u id
)。我想要LOAN.field=123和BORROWER.field='abc'
的记录
这里的答案(例如)似乎是说我应该使用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是{借款人:{字段:abc,贷款:{字段:123}}
//正确
结果2是{借款人:{字段:abc,贷款:{NULL}}
//不正确
当我查看CakePHP使用的SQL时,我没有看到连接。我看到的是两个独立的查询:
查询1:从借款人中选择*/(产生2个ID)
查询2:从借款人id所在的贷款中选择*(id)
这不是我想要的。我想要加入表,然后应用我的条件。我可以很容易地编写SQL查询,但由于我们采用了该框架,我正在尝试以蛋糕式的方式来完成
有可能吗?尝试这样做:
$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} }
您将在本文中找到更多信息。我想我会接受Jose的答案,因为这正是我想要的。但我确实注意到,如果我使用另一个模型作为起点,我不需要任何花哨的技巧——没有连接或包含
借款人
有许多
贷款
s,而贷款
属于
A借款人
。使用贷款
作为我的模型,Cake将自动加入表中,但不使用借款人
$this->Loan->find('all', array( // Not $this->Borrower->find() !
'conditions' => array(
'Borrower.field' => 'abc',
'Loan.field' => 123
)
));