CakePHP find joined records with conditions on each table

杀马特。学长 韩版系。学妹 提交于 2019-12-06 10:41:06

Try to do something like this:

    $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);

You should see a SQL statement like:

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'

Your results will be in an array

{Borrower: {field:abc} LOAN: {field: 123} }

You will find more information in this document.

I think I'll accept Jose's answer because it's exactly what I want. But I did notice that I didn't need any fancy tricks -- no joins or contains -- if I used the other model as my starting point.

A Borrower hasMany Loans, and a Loan belongsTo a Borrower. Using Loan as my model, Cake will automatically join the tables, but not using Borrower.

$this->Loan->find('all', array( // Not $this->Borrower->find() !
'conditions' => array(
    'Borrower.field' => 'abc',
    'Loan.field' => 123
)
));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!