我试图将这个where子句放在我的查询中用Zend 2(Zend \ Db \ Sql):
WHERE `comunity_id` = '$communityId'
AND (
(`date_to` IS NULL AND `date_from` = CURDATE())
OR
(`date_to` IS NOT NULL AND `date_to` >= CURDATE())
)
使用此方法:
public function findByCommunityId($communityId, $limit = 10)
{
$select = $this->getSelect();
$where = new Where();
$select->where(
array(
$where->equalTo('community_id',$communityId), PredicateSet::COMBINED_BY_AND,
new PredicateSet(
array(
new IsNull('date_to'),
$where->equalTo('date_from', new Expression('CURDATE()'))
), PredicateSet::COMBINED_BY_AND
),
PredicateSet::COMBINED_BY_OR,
new PredicateSet(
array(
new IsNotNull('date_to'),
$where->greaterThanOrEqualTo('date_to', new Expression('CURDATE()'))
),
PredicateSet::COMBINED_BY_AND
)
)
);
$select->order(array (
'date_from' => 'ASC'
));
$select->limit($limit);
\Zend\Debug\Debug::dump($select->getSqlString($this->getDbAdapter()->getPlatform()));die;
return $this->select($select);
}
结果是:
SELECT `com_community_events`.*
FROM `com_community_events`
WHERE (`community_id` = '12' AND `date_from` = CURDATE() AND `date_to` >= CURDATE())
AND AND AND (`date_to` IS NULL AND (`community_id` = '12' AND `date_from` = CURDATE() AND `date_to` >= CURDATE())) AND OR AND (`date_to` IS NOT NULL AND (`community_id` = '12' AND `date_from` = CURDATE() AND `date_to` >= CURDATE()))
ORDER BY `date_from` ASC
LIMIT '10'
我的问题是为什么Zend将多个AND / OR关键字放在一起,以及为什么关于community_id
的第一个where子句包含在where子句的另一部分中?
答案 0 :(得分:1)
试试这个 -
注意 - 当然我没有尝试过这个特殊的代码,但这是我通常这样做的方式。如果它不能正常工作,至少它会对nest()
和unnest()
的使用给出一些。
$where = new Where();
$where->nest()
->equalTo('community_id', $communityId)
->and
->nest()
->isNull('date_to')
->and
->equalTo('date_from', new Expression('CURDATE()'))
->unnest()
->or
->nest()
->isNull('date_to')
->and
->greaterThanOrEqualTo('date_from', new Expression('CURDATE()'))
->unnest()
->unnest();
祝你好运。