2017-08-09 19 views
0

你好,我要实现我的查询OR条件,这将是获取从另一个表中的所有记录,其中ID不存在OR取的已记录在过去24小时内插入。选择所有记录,其中ID使用CakePHP 2.x的是不是在另一个表

此查询得到我的最后24小时

 $this->Behaviors->attach('Containable'); 
     return $this->find('all', array(

      'contain' => array(
       'User','UserInfo','QuestionAndTopic.Topic','UpVoteQuestion','Answer' 

      ), 
      'conditions' => array(
       'Question.created >=' => date('Y-m-d H:i:s', strtotime('-24 hour')) 

      ), 

      'order' => 'Question.question_id DESC', 
      'recursive' => 0 
     )); 

结果我想要做这样的事情

$this->Behaviors->attach('Containable'); 
return $this->find('all', array(

    'contain' => array(
     'User','UserInfo','QuestionAndTopic.Topic','UpVoteQuestion','Answer' 

    ), 
    'conditions' => array(
     'OR' => array(
    array('Question.created >=' => date('Y-m-d H:i:s', strtotime('-24 hour'))), 
    array('Question.question_id NOT IN ' => 'Answers'),// get results where question id is not present in answers table as foreign key 
) 



    ), 

    'order' => 'Question.question_id DESC', 
    'recursive' => 0 
)); 

我希望你明白我的问题

+0

阅读:https://book.cakephp.org/2.0/en/models/retrieving-your-data.html#complex-find-conditions – Kenyanke

+0

@Kenyanke你好非常感谢你的分享。我已经理解了大部分部分,但我想知道的一件事是如何检查表中的数据。这里 array('Question.question_id NOT IN'=>'Answers'), – mynameisbutt

+0

你的查询如何知道question_id存在于Answers中? – Kenyanke

回答

0

有几个方法,你可以做到这一点。

1) 您可以使用左连接并检查没有答案的位置。

在SQL:

select * 
from questions 
left join answers on questions.id = answers.question_id 
where answers.id is null; 

在CakePHP:

$this->find('all', array(
    'contain' => array(
     'User','UserInfo','QuestionAndTopic.Topic','UpVoteQuestion','Answer' 
    ), 
    'conditions' => array(
     'OR' => array(
      array('Question.created >=' => date('Y-m-d H:i:s', strtotime('-24 hour'))), 
      array('Answer.id is null'),// get results where question id is not present in answers table as foreign key 
     ) 
    ), 
    'order' => 'Question.question_id DESC', 
    'recursive' => 0 
)); 

2)

您可以使用子查询来加载答案表问题ID列表,并使用基本not in获得补充集。

在SQL:

select * from questions where id not in (select distinct question_id from answers); 

在CakePHP:

子查询中CakePHP的是一个有点复杂。您首先必须设置子查询,然后在查询中调用它。见https://book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries

我从来没有尝试过在条件下使用子查询,但我认为这应该工作。

$db = $this->getDataSource(); 
$subquery = $db->buildStatement(
    array(
     'table' => 'answers', 
     'alias' => 'Answer', 
     'fields' => 'question_id' 
    ), 
    $this 
); 
$this->find('all', array(
    'contain' => array(
     'User','UserInfo','QuestionAndTopic.Topic','UpVoteQuestion','Answer' 
    ), 
    'conditions' => array(
     'OR' => array(
      array('Question.created >=' => date('Y-m-d H:i:s', strtotime('-24 hour'))), 
      array('Question.question_id NOT IN ' => '($subquery)'),// get results where question id is not present in answers table as foreign key 
     ) 
    ), 
    'order' => 'Question.question_id DESC', 
    'recursive' => 0 
)); 
相关问题