diff --git a/lib/Cake/Model/Datasource/Database/Expression/QueryExpression.php b/lib/Cake/Model/Datasource/Database/Expression/QueryExpression.php index 27ea00ba54a..c0ef31a059a 100644 --- a/lib/Cake/Model/Datasource/Database/Expression/QueryExpression.php +++ b/lib/Cake/Model/Datasource/Database/Expression/QueryExpression.php @@ -54,14 +54,17 @@ public function add($conditions, $types = []) { */ public function bind($token, $value, $type) { $param = $token; + $number = count($this->_bindings); if (is_numeric($token)) { $param = '?'; } else if ($param[0] !== ':') { - $param = sprintf(':c%s%s', $this->_identifier, count($this->_bindings)); + $param = sprintf(':c%s%s', $this->_identifier, $number); } - $this->_bindings[$token] = compact('value', 'type') + ['placeholder' => substr($param, 1)]; + $this->_bindings[$number] = compact('value', 'type') + [ + 'placeholder' => substr($param, 1) + ]; return $param; } diff --git a/lib/Cake/Model/Datasource/Database/Query.php b/lib/Cake/Model/Datasource/Database/Query.php index 45e969cf034..03a4e7a59a0 100644 --- a/lib/Cake/Model/Datasource/Database/Query.php +++ b/lib/Cake/Model/Datasource/Database/Query.php @@ -242,7 +242,7 @@ public function where($conditions = null, $types = [], $overwrite = false) { } public function andWhere($conditions, $types = []) { - $where = $this->_parts['where']; + $where = $this->_parts['where'] ?: new QueryExpression(); if ($where->type() === 'AND') { $where->add($conditions, $types); @@ -256,7 +256,7 @@ public function andWhere($conditions, $types = []) { } public function orWhere($conditions, $types = []) { - $where = $this->_parts['where']; + $where = $this->_parts['where'] ?: new QueryExpression([], [], 'OR'); if ($where->type() === 'OR') { $where->add($conditions, $types); diff --git a/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php b/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php index 0938afe514a..cba8372d71b 100644 --- a/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php +++ b/lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php @@ -448,4 +448,23 @@ public function testSelectExpressionNesting() { $this->assertEquals(['id' => 3], $result->fetch('assoc')); } +/** + * Tests that Query::orWhere() can be used without calling where() before + * + * @return void + **/ + public function testSelectOrWhereNoPreviousCondition() { + $this->_insertDateRecords(); + $query = new Query($this->connection); + $result = $query + ->select(['id']) + ->from('dates') + ->orWhere(['posted' => new \DateTime('2012-12-21 12:00')], ['posted' => 'datetime']) + ->orWhere(['posted' => new \DateTime('2012-12-22 12:00')], ['posted' => 'datetime']) + ->execute(); + $this->assertCount(2, $result); + $this->assertEquals(['id' => 1], $result->fetch('assoc')); + $this->assertEquals(['id' => 2], $result->fetch('assoc')); + } + }