【问题标题】:CakePHP find joined records with conditions on each tableCakePHP 在每个表上查找带有条件的连接记录
【发布时间】:2013-04-29 18:30:16
【问题描述】:

我想查看连接中的所有记录,在连接的每一侧设置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 的方式进行。

有可能吗?

【问题讨论】:

    标签: cakephp join cakephp-2.0


    【解决方案1】:

    尝试做这样的事情:

        $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 中找到更多信息。

    【讨论】:

      【解决方案2】:

      我想我会接受 Jose 的回答,因为这正是我想要的。但我确实注意到,如果我使用 other 模型作为我的起点,我不需要任何花哨的技巧——没有连接或包含。

      BorrowerhasManyLoans,LoanbelongsToBorrower。使用Loan 作为我的模型,Cake 会自动加入表格,但不会使用Borrower

      $this->Loan->find('all', array( // Not $this->Borrower->find() !
      'conditions' => array(
          'Borrower.field' => 'abc',
          'Loan.field' => 123
      )
      ));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多