Example #1
0
 public function testWhere()
 {
     $query = new Query();
     $query->where('id = :id', [':id' => 1]);
     $this->assertEquals('id = :id', $query->where);
     $this->assertEquals([':id' => 1], $query->params);
     $query->andWhere('name = :name', [':name' => 'something']);
     $this->assertEquals(['and', 'id = :id', 'name = :name'], $query->where);
     $this->assertEquals([':id' => 1, ':name' => 'something'], $query->params);
     $query->orWhere('age = :age', [':age' => '30']);
     $this->assertEquals(['or', ['and', 'id = :id', 'name = :name'], 'age = :age'], $query->where);
     $this->assertEquals([':id' => 1, ':name' => 'something', ':age' => '30'], $query->params);
 }
Example #2
0
 /**
  * Generates a SELECT SQL statement from a [[Query]] object.
  * @param Query $query the [[Query]] object from which the SQL statement will be generated
  * @param array $params the parameters to be bound to the generated SQL statement. These parameters will
  * be included in the result with the additional parameters generated during the query building process.
  * @return array the generated SQL statement (the first array element) and the corresponding
  * parameters to be bound to the SQL statement (the second array element). The parameters returned
  * include those provided in `$params`.
  */
 public function build($query, $params = [])
 {
     $params = empty($params) ? $query->params : array_merge($params, $query->params);
     if ($query->match !== null) {
         if ($query->match instanceof Expression) {
             $query->andWhere('MATCH(' . $query->match->expression . ')');
             $params = array_merge($params, $query->match->params);
         } else {
             $phName = self::PARAM_PREFIX . count($params);
             $params[$phName] = $this->db->escapeMatchValue($query->match);
             $query->andWhere('MATCH(' . $phName . ')');
         }
     }
     $from = $query->from;
     if ($from === null && $query instanceof ActiveQuery) {
         /** @var ActiveRecord $modelClass */
         $modelClass = $query->modelClass;
         $from = [$modelClass::indexName()];
     }
     $clauses = [$this->buildSelect($query->select, $params, $query->distinct, $query->selectOption), $this->buildFrom($from, $params), $this->buildWhere($query->from, $query->where, $params), $this->buildGroupBy($query->groupBy), $this->buildWithin($query->within), $this->buildOrderBy($query->orderBy), $this->buildLimit($query->limit, $query->offset), $this->buildOption($query->options, $params)];
     return [implode($this->separator, array_filter($clauses)), $params];
 }