Class yii\sphinx\ActiveQuery

Inheritanceyii\sphinx\ActiveQuery » yii\sphinx\Query » yii\db\Query
Implementsyii\db\ActiveQueryInterface
Uses Traitsyii\db\ActiveQueryTrait, yii\db\ActiveRelationTrait
Available since extension's version2.0
Source Code https://github.com/yiisoft/yii2-sphinx/blob/master/src/ActiveQuery.php

ActiveQuery represents a Sphinx query associated with an Active Record class.

An ActiveQuery can be a normal query or be used in a relational context.

ActiveQuery instances are usually created by yii\sphinx\ActiveRecord::find() and yii\sphinx\ActiveRecord::findBySql(). Relational queries are created by ActiveRecord::hasOne() and ActiveRecord::hasMany().

Normal Query

Because ActiveQuery extends from yii\sphinx\Query, one can use query methods, such as where(), orderBy() to customize the query options.

ActiveQuery also provides the following additional query options:

  • with(): list of relations that this query should be performed with.
  • indexBy(): the name of the column by which the query result should be indexed.
  • asArray(): whether to return each record as an array.

These options can be configured using methods of the same name. For example:

$articles = Article::find()->with('source')->asArray()->all();

ActiveQuery allows to build the snippets using sources provided by ActiveRecord. You can use snippetByModel() method to enable this. For example:

class Article extends ActiveRecord
{
    public function getSource()
    {
        return $this->hasOne('db', ArticleDb::className(), ['id' => 'id']);
    }

    public function getSnippetSource()
    {
        return $this->source->content;
    }

    ...
}

$articles = Article::find()->with('source')->snippetByModel()->all();

Relational query

In relational context ActiveQuery represents a relation between two Active Record classes.

Relational ActiveQuery instances are usually created by calling ActiveRecord::hasOne() and ActiveRecord::hasMany(). An Active Record class declares a relation by defining a getter method which calls one of the above methods and returns the created ActiveQuery object.

A relation is specified by link which represents the association between columns of different tables; and the multiplicity of the relation is indicated by multiple.

If a relation involves a junction table, it may be specified by via(). This methods may only be called in a relational context. Same is true for inverseOf(), which marks a relation as inverse of another relation.

Public Properties

Hide inherited properties

Property Type Description Defined By
$connection yii\sphinx\Connection Sphinx connection instance. yii\sphinx\Query
$facets array Facet search specifications. yii\sphinx\Query
$groupLimit integer Groups limit: to return (no more than) N top matches for each group. yii\sphinx\Query
$match string|\yii\db\Expression Text, which should be searched in fulltext mode. yii\sphinx\Query
$options array Per-query options in format: optionName => optionValue They will compose OPTION clause. yii\sphinx\Query
$showMeta boolean|string|\yii\db\Expression Whether to automatically perform 'SHOW META' query against main one. yii\sphinx\Query
$snippetCallback callable PHP callback, which should be used to fetch source data for the snippets. yii\sphinx\Query
$snippetOptions array Query options for the call snippet. yii\sphinx\Query
$sql string The SQL statement to be executed for retrieving AR records. yii\sphinx\ActiveQuery
$within string WITHIN GROUP ORDER BY clause. yii\sphinx\Query

Public Methods

Hide inherited methods

Method Description Defined By
__construct() Constructor. yii\sphinx\ActiveQuery
addFacets() Adds additional FACET part of the query. yii\sphinx\Query
addOptions() Adds additional query options. yii\sphinx\Query
addWithin() Adds additional WITHIN GROUP ORDER BY columns to the query. yii\sphinx\Query
all() Executes query and returns all results as an array. yii\sphinx\ActiveQuery
create() Creates a new Query object and copies its property values from an existing one. yii\sphinx\Query
createCommand() Creates a DB command that can be used to execute this query. yii\sphinx\ActiveQuery
facets() Sets FACET part of the query. yii\sphinx\Query
getConnection() yii\sphinx\Query
getTablesUsedInFrom() yii\sphinx\Query
groupLimit() Sets groups limit: to return (no more than) N top matches for each group. yii\sphinx\Query
init() Initializes the object. yii\sphinx\ActiveQuery
innerJoin() yii\sphinx\Query
join() yii\sphinx\Query
leftJoin() yii\sphinx\Query
match() Sets the fulltext query text. This text will be composed into MATCH operator inside the WHERE clause. yii\sphinx\Query
one() Executes query and returns a single row of result. yii\sphinx\ActiveQuery
options() Sets the query options. yii\sphinx\Query
populate() yii\sphinx\ActiveQuery
rightJoin() yii\sphinx\Query
search() Executes the query and returns the complete search result including e.g. hits, facets. yii\sphinx\Query
setConnection() yii\sphinx\Query
showMeta() Sets whether to automatically perform 'SHOW META' for the search query. yii\sphinx\Query
snippetByModel() Sets the snippetCallback() to fetchSnippetSourceFromModels(), which allows to fetch the snippet source strings from the Active Record models, using method yii\sphinx\ActiveRecord::getSnippetSource(). yii\sphinx\ActiveQuery
snippetCallback() Sets the PHP callback, which should be used to retrieve the source data for the snippets building. yii\sphinx\Query
snippetOptions() Sets the call snippets query options. yii\sphinx\Query
within() Sets the WITHIN GROUP ORDER BY part of the query. yii\sphinx\Query

Protected Methods

Hide inherited methods

Method Description Defined By
callSnippets() Builds a snippets from provided source data. yii\sphinx\ActiveQuery
callSnippetsInternal() Builds a snippets from provided source data by the given index. yii\sphinx\Query
defaultConnection() yii\sphinx\ActiveQuery
fetchSnippetSourceFromModels() Fetches the source for the snippets using yii\sphinx\ActiveRecord::getSnippetSource() method. yii\sphinx\ActiveQuery
fillUpSnippets() Fills the query result rows with the snippets built from source determined by snippetCallback() result. yii\sphinx\Query
queryScalar() yii\sphinx\Query

Events

Hide inherited events

Event Type Description Defined By
EVENT_INIT yii\sphinx\Event An event that is triggered when the query is initialized via init(). yii\sphinx\ActiveQuery

Property Details

Hide inherited properties

$sql public property

The SQL statement to be executed for retrieving AR records. This is set by yii\sphinx\ActiveRecord::findBySql().

public string $sql null

Method Details

Hide inherited methods

__construct() public method

Constructor.

public void __construct ( $modelClass, $config = [] )
$modelClass array

The model class associated with this query

$config array

Configurations to be applied to the newly created query object

                public function __construct($modelClass, $config = [])
{
    $this->modelClass = $modelClass;
    parent::__construct($config);
}

            
addFacets() public method

Defined in: yii\sphinx\Query::addFacets()

Adds additional FACET part of the query.

public $this addFacets ( $facets )
$facets array

Facet specifications.

return $this

The query object itself

                public function addFacets($facets)
{
    if (is_array($this->facets)) {
        $this->facets = array_merge($this->facets, $facets);
    } else {
        $this->facets = $facets;
    }
    return $this;
}

            
addOptions() public method

Defined in: yii\sphinx\Query::addOptions()

Adds additional query options.

See also options().

public $this addOptions ( $options )
$options array

Query options in format: optionName => optionValue

return $this

The query object itself

                public function addOptions($options)
{
    if (is_array($this->options)) {
        $this->options = array_merge($this->options, $options);
    } else {
        $this->options = $options;
    }
    return $this;
}

            
addWithin() public method

Defined in: yii\sphinx\Query::addWithin()

Adds additional WITHIN GROUP ORDER BY columns to the query.

See also within().

public $this addWithin ( $columns )
$columns string|array

The columns (and the directions) to find best row within a group. Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g. ['id' => Query::SORT_ASC, 'name' => Query::SORT_DESC]). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).

return $this

The query object itself

                public function addWithin($columns)
{
    $columns = $this->normalizeOrderBy($columns);
    if ($this->within === null) {
        $this->within = $columns;
    } else {
        $this->within = array_merge($this->within, $columns);
    }
    return $this;
}

            
all() public method

Executes query and returns all results as an array.

public array|yii\sphinx\ActiveRecord[] all ( $db null )
$db yii\sphinx\Connection

The DB connection used to create the DB command. If null, the DB connection returned by modelClass will be used.

return array|yii\sphinx\ActiveRecord[]

The query results. If the query results in nothing, an empty array will be returned.

                public function all($db = null)
{
    return parent::all($db);
}

            
callSnippets() protected method

Builds a snippets from provided source data.

protected array callSnippets ( array $source )
$source array

The source data to extract a snippet from.

return array

Snippets list.

throws \yii\base\InvalidCallException

in case match() is not specified.

                protected function callSnippets(array $source)
{
    $from = $this->from;
    if ($from === null) {
        /* @var $modelClass ActiveRecord */
        $modelClass = $this->modelClass;
        $tableName = $modelClass::indexName();
        $from = [$tableName];
    }
    return $this->callSnippetsInternal($source, $from[0]);
}

            
callSnippetsInternal() protected method

Defined in: yii\sphinx\Query::callSnippetsInternal()

Builds a snippets from provided source data by the given index.

protected array callSnippetsInternal ( array $source, $from )
$source array

The source data to extract a snippet from.

$from string

Name of the source index.

return array

Snippets list.

throws \yii\base\InvalidCallException

in case match() is not specified.

                protected function callSnippetsInternal(array $source, $from)
{
    $connection = $this->getConnection();
    $match = $this->match;
    if ($match === null) {
        throw new InvalidCallException('Unable to call snippets: "' . $this->className() . '::match" should be specified.');
    }
    return $connection->createCommand()
        ->callSnippets($from, $source, $match, $this->snippetOptions)
        ->queryColumn();
}

            
create() public static method

Defined in: yii\sphinx\Query::create()

Creates a new Query object and copies its property values from an existing one.

The properties being copies are the ones to be used by query builders.

public static yii\sphinx\Query create ( $from )
$from yii\sphinx\Query

The source query object

return yii\sphinx\Query

The new Query object

                public static function create($from)
{
    return new self([
        'where' => $from->where,
        'limit' => $from->limit,
        'offset' => $from->offset,
        'orderBy' => $from->orderBy,
        'indexBy' => $from->indexBy,
        'select' => $from->select,
        'selectOption' => $from->selectOption,
        'distinct' => $from->distinct,
        'from' => $from->from,
        'groupBy' => $from->groupBy,
        'join' => $from->join,
        'having' => $from->having,
        'union' => $from->union,
        'params' => $from->params,
        // Sphinx specifics :
        'groupLimit' => $from->groupLimit,
        'options' => $from->options,
        'within' => $from->within,
        'match' => $from->match,
        'snippetCallback' => $from->snippetCallback,
        'snippetOptions' => $from->snippetOptions,
    ]);
}

            
createCommand() public method

Creates a DB command that can be used to execute this query.

public yii\sphinx\Command createCommand ( $db null )
$db yii\sphinx\Connection

The DB connection used to create the DB command. If null, the DB connection returned by modelClass will be used.

return yii\sphinx\Command

The created DB command instance.

                public function createCommand($db = null)
{
    if ($this->primaryModel !== null) {
        // lazy loading a relational query
        if ($this->via instanceof self) {
            // via pivot index
            $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
            $this->filterByModels($viaModels);
        } elseif (is_array($this->via)) {
            // via relation
            /* @var $viaQuery ActiveQuery */
            list($viaName, $viaQuery) = $this->via;
            if ($viaQuery->multiple) {
                $viaModels = $viaQuery->all();
                $this->primaryModel->populateRelation($viaName, $viaModels);
            } else {
                $model = $viaQuery->one();
                $this->primaryModel->populateRelation($viaName, $model);
                $viaModels = $model === null ? [] : [$model];
            }
            $this->filterByModels($viaModels);
        } else {
            $this->filterByModels([$this->primaryModel]);
        }
    }
    $this->setConnection($db);
    $db = $this->getConnection();
    if ($this->sql === null) {
        list ($sql, $params) = $db->getQueryBuilder()->build($this);
    } else {
        $sql = $this->sql;
        $params = $this->params;
    }
    return $db->createCommand($sql, $params);
}

            
defaultConnection() protected method

protected yii\sphinx\Connection defaultConnection ( )
return yii\sphinx\Connection

Default connection value.

                protected function defaultConnection()
{
    $modelClass = $this->modelClass;
    return $modelClass::getDb();
}

            
facets() public method

Defined in: yii\sphinx\Query::facets()

Sets FACET part of the query.

public $this facets ( $facets )
$facets array

Facet specifications.

return $this

The query object itself

                public function facets($facets)
{
    $this->facets = $facets;
    return $this;
}

            
fetchSnippetSourceFromModels() protected method

Fetches the source for the snippets using yii\sphinx\ActiveRecord::getSnippetSource() method.

protected array fetchSnippetSourceFromModels ( $models )
$models yii\sphinx\ActiveRecord[]

Raw query result rows.

return array

Snippet source strings

throws \yii\base\InvalidCallException

if asArray enabled.

                protected function fetchSnippetSourceFromModels($models)
{
    if ($this->asArray) {
        throw new InvalidCallException('"' . __METHOD__ . '" unable to determine snippet source from plain array. Either disable "asArray" option or use regular "snippetCallback"');
    }
    $result = [];
    foreach ($models as $model) {
        $result[] = $model->getSnippetSource();
    }
    return $result;
}

            
fillUpSnippets() protected method

Defined in: yii\sphinx\Query::fillUpSnippets()

Fills the query result rows with the snippets built from source determined by snippetCallback() result.

protected array|yii\sphinx\ActiveRecord[] fillUpSnippets ( $rows )
$rows array

Raw query result rows.

return array|yii\sphinx\ActiveRecord[]

Query result rows with filled up snippets.

                protected function fillUpSnippets($rows)
{
    if ($this->snippetCallback === null || empty($rows)) {
        return $rows;
    }
    $snippetSources = call_user_func($this->snippetCallback, $rows);
    $snippets = $this->callSnippets($snippetSources);
    $snippetKey = 0;
    foreach ($rows as $key => $row) {
        $rows[$key]['snippet'] = $snippets[$snippetKey];
        $snippetKey++;
    }
    return $rows;
}

            
getConnection() public method
public yii\sphinx\Connection getConnection ( )
return yii\sphinx\Connection

Sphinx connection instance

                public function getConnection()
{
    if ($this->_connection === null) {
        $this->_connection = $this->defaultConnection();
    }
    return $this->_connection;
}

            
getTablesUsedInFrom() public method (available since version 2.0.9)
public void getTablesUsedInFrom ( )

                public function getTablesUsedInFrom()
{
    // feature not supported, returning a stub:
    return [];
}

            
groupLimit() public method (available since version 2.0.6)

Defined in: yii\sphinx\Query::groupLimit()

Sets groups limit: to return (no more than) N top matches for each group.

This option will take effect only if groupBy is set.

public $this groupLimit ( $limit )
$limit integer

Group limit.

return $this

The query object itself.

                public function groupLimit($limit)
{
    $this->groupLimit = $limit;
    return $this;
}

            
init() public method

Initializes the object.

This method is called at the end of the constructor. The default implementation will trigger an EVENT_INIT event. If you override this method, make sure you call the parent implementation at the end to ensure triggering of the event.

public void init ( )

                public function init()
{
    parent::init();
    $this->trigger(self::EVENT_INIT);
}

            
innerJoin() public method
public void innerJoin ( $table, $on '', $params = [] )
$table
$on
$params

                public function innerJoin($table, $on = '', $params = [])
{
    throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}

            
join() public method
public void join ( $type, $table, $on '', $params = [] )
$type
$table
$on
$params

                public function join($type, $table, $on = '', $params = [])
{
    throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}

            
leftJoin() public method
public void leftJoin ( $table, $on '', $params = [] )
$table
$on
$params

                public function leftJoin($table, $on = '', $params = [])
{
    throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}

            
match() public method

Defined in: yii\sphinx\Query::match()

Sets the fulltext query text. This text will be composed into MATCH operator inside the WHERE clause.

Note: this value will be processed by yii\sphinx\Connection::escapeMatchValue(), if you need to compose complex match condition use Expression:

$query = new Query();
$query->from('my_index')
    ->match(new Expression(':match', ['match' => '@(content) ' . Yii::$app->sphinx->escapeMatchValue($matchValue)]))
    ->all();
public $this match ( $query )
$query string|\yii\db\Expression|yii\sphinx\MatchExpression

Fulltext query text.

return $this

The query object itself.

                public function match($query)
{
    $this->match = $query;
    return $this;
}

            
one() public method

Executes query and returns a single row of result.

public yii\sphinx\ActiveRecord|array|null one ( $db null )
$db yii\sphinx\Connection

The DB connection used to create the DB command. If null, the DB connection returned by modelClass will be used.

return yii\sphinx\ActiveRecord|array|null

A single row of query result. Depending on the setting of asArray, the query result may be either an array or an ActiveRecord object. Null will be returned if the query results in nothing.

                public function one($db = null)
{
    $row = parent::one($db);
    if ($row !== false) {
        $models = $this->populate([$row]);
        return reset($models) ?: null;
    } else {
        return null;
    }
}

            
options() public method

Defined in: yii\sphinx\Query::options()

Sets the query options.

See also addOptions().

public $this options ( $options )
$options array

Query options in format: optionName => optionValue

return $this

The query object itself

                public function options($options)
{
    $this->options = $options;
    return $this;
}

            
populate() public method

public void populate ( $rows )
$rows

                public function populate($rows)
{
    if (empty($rows)) {
        return [];
    }
    $models = $this->createModels($rows);
    if (!empty($this->with)) {
        $this->findWith($this->with, $models);
    }
    $models = parent::populate($models);
    if (!$this->asArray) {
        foreach ($models as $model) {
            $model->afterFind();
        }
    }
    return $models;
}

            
queryScalar() protected method
protected void queryScalar ( $selectExpression, $db )
$selectExpression
$db

                protected function queryScalar($selectExpression, $db)
{
    if (!empty($this->emulateExecution)) {
        return null;
    }
    $select = $this->select;
    $limit = $this->limit;
    $offset = $this->offset;
    $this->select = [$selectExpression];
    $this->limit = null;
    $this->offset = null;
    $command = $this->createCommand($db);
    $this->select = $select;
    $this->limit = $limit;
    $this->offset = $offset;
    if (empty($this->groupBy) && empty($this->union) && !$this->distinct) {
        return $command->queryScalar();
    }
    return (new Query)->select([$selectExpression])
        ->from(['c' => $this])
        ->createCommand($command->db)
        ->queryScalar();
}

            
rightJoin() public method
public void rightJoin ( $table, $on '', $params = [] )
$table
$on
$params

                public function rightJoin($table, $on = '', $params = [])
{
    throw new NotSupportedException('"' . __METHOD__ . '" is not supported.');
}

            
search() public method

Defined in: yii\sphinx\Query::search()

Executes the query and returns the complete search result including e.g. hits, facets.

public array search ( $db null )
$db yii\sphinx\Connection

The Sphinx connection used to generate the SQL statement.

return array

The query results.

                public function search($db = null)
{
    if (!empty($this->emulateExecution)) {
        return [
            'hits' => [],
            'facets' => [],
            'meta' => [],
        ];
    }
    $command = $this->createCommand($db);
    $dataReader = $command->query();
    $rawRows = $dataReader->readAll();
    $facets = [];
    foreach ($this->facets as $facetKey => $facetValue) {
        $dataReader->nextResult();
        $rawFacetResults = $dataReader->readAll();
        if (is_numeric($facetKey)) {
            $facet = [
                'name' => $facetValue,
                'value' => $facetValue,
                'count' => 'count(*)',
            ];
        } else {
            $facet = array_merge(
                [
                    'name' => $facetKey,
                    'value' => $facetKey,
                    'count' => 'count(*)',
                ],
                $facetValue
            );
        }
        foreach ($rawFacetResults as $rawFacetResult) {
            $rawFacetResult['value'] = isset($rawFacetResult[strtolower($facet['value'])]) ? $rawFacetResult[strtolower($facet['value'])] : null;
            $rawFacetResult['count'] = $rawFacetResult[$facet['count']];
            $facets[$facet['name']][] = $rawFacetResult;
        }
    }
    $meta = [];
    if (!empty($this->showMeta)) {
        $dataReader->nextResult();
        $rawMetaResults = $dataReader->readAll();
        foreach ($rawMetaResults as $rawMetaResult) {
            $meta[$rawMetaResult['Variable_name']] = $rawMetaResult['Value'];
        }
    }
    // rows should be populated after all data read from cursor, avoiding possible 'unbuffered query' error
    $rows = $this->populate($rawRows);
    return [
        'hits' => $rows,
        'facets' => $facets,
        'meta' => $meta,
    ];
}

            
setConnection() public method
public $this setConnection ( $connection )
$connection yii\sphinx\Connection

Sphinx connection instance

return $this

The query object itself

                public function setConnection($connection)
{
    $this->_connection = $connection;
    return $this;
}

            
showMeta() public method

Defined in: yii\sphinx\Query::showMeta()

Sets whether to automatically perform 'SHOW META' for the search query.

See also showMeta().

public $this showMeta ( $showMeta )
$showMeta boolean|string|\yii\db\Expression

Whether to automatically perform 'SHOW META'

return $this

The query object itself

                public function showMeta($showMeta)
{
    $this->showMeta = $showMeta;
    return $this;
}

            
snippetByModel() public method

Sets the snippetCallback() to fetchSnippetSourceFromModels(), which allows to fetch the snippet source strings from the Active Record models, using method yii\sphinx\ActiveRecord::getSnippetSource().

For example:

class Article extends ActiveRecord
{
    public function getSnippetSource()
    {
        return file_get_contents('/path/to/source/files/' . $this->id . '.txt');;
    }
}

$articles = Article::find()->snippetByModel()->all();

Warning: this option should NOT be used with asArray at the same time!

public $this snippetByModel ( )
return $this

The query object itself

                public function snippetByModel()
{
    $this->snippetCallback([$this, 'fetchSnippetSourceFromModels']);
    return $this;
}

            
snippetCallback() public method

Defined in: yii\sphinx\Query::snippetCallback()

Sets the PHP callback, which should be used to retrieve the source data for the snippets building.

See also snippetCallback().

public $this snippetCallback ( $callback )
$callback callable

PHP callback, which should be used to fetch source data for the snippets.

return $this

The query object itself

                public function snippetCallback($callback)
{
    $this->snippetCallback = $callback;
    return $this;
}

            
snippetOptions() public method

Defined in: yii\sphinx\Query::snippetOptions()

Sets the call snippets query options.

See also snippetCallback().

public $this snippetOptions ( $options )
$options array

Call snippet options in format: option_name => option_value

return $this

The query object itself

                public function snippetOptions($options)
{
    $this->snippetOptions = $options;
    return $this;
}

            
within() public method

Defined in: yii\sphinx\Query::within()

Sets the WITHIN GROUP ORDER BY part of the query.

See also addWithin().

public $this within ( $columns )
$columns string|array

The columns (and the directions) to find best row within a group. Columns can be specified in either a string (e.g. "id ASC, name DESC") or an array (e.g. ['id' => Query::SORT_ASC, 'name' => Query::SORT_DESC]). The method will automatically quote the column names unless a column contains some parenthesis (which means the column contains a DB expression).

return $this

The query object itself

                public function within($columns)
{
    $this->within = $this->normalizeOrderBy($columns);
    return $this;
}

            

Event Details

Hide inherited properties

EVENT_INIT event of type yii\sphinx\Event

An event that is triggered when the query is initialized via init().