4 追蹤者

類別 yii\db\ActiveQuery

繼承關係yii\db\ActiveQuery » yii\db\Query » yii\base\Component » yii\base\BaseObject
實作介面yii\base\Configurable, yii\db\ActiveQueryInterface, yii\db\ExpressionInterface, yii\db\QueryInterface
使用 Traityii\db\ActiveQueryTrait, yii\db\ActiveRelationTrait, yii\db\QueryTrait
自版本2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/db/ActiveQuery.php

ActiveQuery 代表與 ActiveRecord 類別相關聯的資料庫查詢。

ActiveQuery 可以是一般查詢,也可以在關聯式上下文中使用。

ActiveQuery 實例通常由 yii\db\ActiveRecord::find()yii\db\ActiveRecord::findBySql() 建立。關聯式查詢由 yii\db\ActiveRecord::hasOne()yii\db\ActiveRecord::hasMany() 建立。

一般查詢

ActiveQuery 主要提供以下方法來檢索查詢結果

  • one():傳回以第一筆資料列填充的單一記錄。
  • all():傳回所有基於查詢結果的記錄。
  • count():傳回記錄數。
  • sum():傳回指定欄位的總和。
  • average():傳回指定欄位的平均值。
  • min():傳回指定欄位的最小值。
  • max():傳回指定欄位的最大值。
  • scalar():傳回查詢結果第一列中第一欄的值。
  • column():傳回查詢結果第一欄的值。
  • exists():傳回一個值,指示查詢結果是否包含資料。

由於 ActiveQuery 繼承自 yii\db\Query,因此可以使用查詢方法,例如 where()orderBy() 來自訂查詢選項。

ActiveQuery 也提供以下額外的查詢選項

  • with():此查詢應執行的關聯清單。
  • joinWith():重複使用關聯查詢定義以將 join 新增至查詢。
  • indexBy():應作為查詢結果索引的欄位名稱。
  • asArray():是否將每個記錄作為陣列傳回。

這些選項可以使用相同名稱的方法進行配置。例如

$customers = Customer::find()->with('orders')->asArray()->all();

關聯式查詢

在關聯式上下文中,ActiveQuery 代表兩個 ActiveRecord 類別之間的關聯。

關聯式 ActiveQuery 實例通常透過呼叫 yii\db\ActiveRecord::hasOne()yii\db\ActiveRecord::hasMany() 建立。Active Record 類別透過定義一個 getter 方法來宣告關聯,該方法呼叫上述方法之一並傳回建立的 ActiveQuery 物件。

關聯由 $link 指定,它代表不同表格的欄位之間的關聯;關聯的多重性由 $multiple 指示。

如果關聯涉及聯結表,則可以使用 via()viaTable() 方法指定。這些方法只能在關聯式上下文中使用。inverseOf() 也是如此,它將關聯標記為另一個關聯的反向關聯,而 onCondition() 則新增一個條件,該條件將新增至關聯式查詢聯結條件。

公共屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$asArray 布林值 是否將每筆記錄作為陣列回傳。 yii\db\ActiveQueryTrait
$behaviors yii\base\Behavior[] 附加到此元件的行為列表。 yii\base\Component
$distinct 布林值 是否僅選取不重複的資料列。 yii\db\Query
$emulateExecution 布林值 是否模擬實際的查詢執行,回傳空的或 false 結果。 yii\db\QueryTrait
$from array|null 要從中選取的資料表。 yii\db\Query
$groupBy array|null 如何將查詢結果分組。 yii\db\Query
$having string|array|yii\db\ExpressionInterface|null 要套用於 GROUP BY 子句的條件。 yii\db\Query
$indexBy string|callable|null 應作為查詢結果索引依據的欄位名稱。 yii\db\QueryTrait
$inverseOf string 作為此關聯反向關聯的關聯名稱。 yii\db\ActiveRelationTrait
$join array|null 如何與其他資料表進行聯結。 yii\db\Query
$joinWith array|null 此查詢應聯結的關聯列表 yii\db\ActiveQuery
$limit integer|yii\db\ExpressionInterface|null 要回傳的最大記錄數。 yii\db\QueryTrait
$modelClass string ActiveRecord 類別的名稱。 yii\db\ActiveQueryTrait
$multiple 布林值 此查詢是否表示與多個記錄的關聯。 yii\db\ActiveRelationTrait
$offset integer|yii\db\ExpressionInterface|null 從何處開始回傳記錄的從零開始的偏移量。 yii\db\QueryTrait
$on string|array|null 當此查詢用於關聯內容時,要使用的聯結條件。 yii\db\ActiveQuery
$orderBy array|null 如何排序查詢結果。 yii\db\QueryTrait
$params array|null 依參數預留位置索引的查詢參數值列表。 yii\db\Query
$primaryModel yii\db\ActiveRecord 關聯式查詢的主要模型。 yii\db\ActiveRelationTrait
$queryCacheDependency yii\caching\Dependency|null 要與此查詢的快取查詢結果相關聯的依賴性 yii\db\Query
$queryCacheDuration integer|boolean|null 查詢結果在快取中保持有效的預設秒數。 yii\db\Query
$select array|null 正在選取的欄位。 yii\db\Query
$selectOption string|null 應附加到 'SELECT' 關鍵字的額外選項。 yii\db\Query
$sql string|null 要執行以檢索 AR 記錄的 SQL 陳述式。 yii\db\ActiveQuery
$tablesUsedInFrom string[] 依別名索引的資料表名稱。 yii\db\Query
$union array|null 這用於建構 SQL 陳述式中的 UNION 子句。 yii\db\Query
$via array|object 與連接資料表相關聯的查詢。 yii\db\ActiveRelationTrait
$where string|array|yii\db\ExpressionInterface|null 查詢條件。 yii\db\QueryTrait
$with array 此查詢應執行的關聯列表 yii\db\ActiveQueryTrait
$withQueries array|null 這用於建構 SQL 查詢中的 WITH 區段。 yii\db\Query

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫非類別方法的具名方法。 yii\base\Component
__clone() 複製內部物件。 yii\db\ActiveRelationTrait
__construct() 建構子。 yii\db\ActiveQuery
__get() 回傳元件屬性的值。 yii\base\Component
__isset() 檢查是否已設定屬性,即已定義且非 null。 yii\base\Component
__set() 設定元件屬性的值。 yii\base\Component
__toString() 回傳 Query 的 SQL 表示法 yii\db\Query
__unset() 將元件屬性設定為 null。 yii\base\Component
addGroupBy() 將額外的 group-by 欄位新增到現有的欄位。 yii\db\Query
addOrderBy() 將額外的 ORDER BY 欄位新增到查詢中。 yii\db\QueryTrait
addParams() 新增要繫結到查詢的額外參數。 yii\db\Query
addSelect() 將更多欄位新增到查詢的 SELECT 部分。 yii\db\Query
alias() $modelClass 中定義的資料表定義別名。 yii\db\ActiveQuery
all() 執行查詢並以陣列形式回傳所有結果。 yii\db\ActiveQuery
andFilterCompare() 為特定欄位新增篩選條件,並允許使用者選擇篩選運算子。 yii\db\Query
andFilterHaving() 將額外的 HAVING 條件新增到現有的條件,但忽略空運算元 yii\db\Query
andFilterWhere() 將額外的 WHERE 條件新增到現有的條件,但忽略空運算元 yii\db\QueryTrait
andHaving() 將額外的 HAVING 條件新增到現有的條件。 yii\db\Query
andOnCondition() 將額外的 ON 條件新增到現有的條件。 yii\db\ActiveQuery
andWhere() 將額外的 WHERE 條件新增到現有的條件。 yii\db\QueryTrait
asArray() 設定 asArray() 屬性。 yii\db\ActiveQueryTrait
attachBehavior() 將行為附加到此元件。 yii\base\Component
attachBehaviors() 將行為列表附加到元件。 yii\base\Component
average() 回傳指定欄位值的平均值。 yii\db\Query
batch() 開始批次查詢。 yii\db\Query
behaviors() 回傳此元件應表現為的行為列表。 yii\base\Component
cache() 為此 Query 啟用查詢快取。 yii\db\Query
canGetProperty() 回傳一個值,指示是否可以讀取屬性。 yii\base\Component
canSetProperty() 回傳一個值,指示是否可以設定屬性。 yii\base\Component
className() 回傳此類別的完整命名空間名稱。 yii\base\BaseObject
column() 執行查詢並回傳結果的第一個欄位。 yii\db\Query
count() 回傳記錄數。 yii\db\Query
create() 建立新的 Query 物件,並從現有的物件複製其屬性值。 yii\db\Query
createCommand() 建立可用於執行此查詢的 DB 命令。 yii\db\ActiveQuery
detachBehavior() 從元件卸離行為。 yii\base\Component
detachBehaviors() 從元件卸離所有行為。 yii\base\Component
distinct() 設定是否選取 DISTINCT 的值。 yii\db\Query
each() 開始批次查詢並逐列檢索資料。 yii\db\Query
emulateExecution() 設定是否模擬查詢執行,防止與資料儲存進行任何互動。 yii\db\QueryTrait
ensureBehaviors() 確保在 behaviors() 中宣告的行為已附加到此元件。 yii\base\Component
exists() 回傳一個值,指示查詢結果是否包含任何資料列。 yii\db\Query
filterHaving() 設定查詢的 HAVING 部分,但忽略空運算元 yii\db\Query
filterWhere() 設定查詢的 WHERE 部分,但忽略空運算元 yii\db\QueryTrait
findFor() 尋找指定主要記錄的相關記錄。 yii\db\ActiveRelationTrait
findWith() 尋找對應於一個或多個關聯的記錄,並將其填入主要模型。 yii\db\ActiveQueryTrait
from() 設定查詢的 FROM 部分。 yii\db\Query
getBehavior() 回傳具名的行為物件。 yii\base\Component
getBehaviors() 回傳附加到此元件的所有行為。 yii\base\Component
getTablesUsedInFrom() 回傳在 from() 中使用的資料表名稱,依別名索引。 yii\db\ActiveQuery
groupBy() 設定查詢的 GROUP BY 部分。 yii\db\Query
hasEventHandlers() 回傳一個值,指示是否有名稱事件附加任何處理常式。 yii\base\Component
hasMethod() 回傳一個值,指示是否已定義方法。 yii\base\Component
hasProperty() 回傳一個值,指示是否為此元件定義了屬性。 yii\base\Component
having() 設定查詢的 HAVING 部分。 yii\db\Query
indexBy() 設定 indexBy() 屬性。 yii\db\QueryTrait
init() 初始化物件。 yii\db\ActiveQuery
innerJoin() 將 INNER JOIN 部分附加到查詢。 yii\db\Query
innerJoinWith() 與指定的關聯進行內部聯結。 yii\db\ActiveQuery
inverseOf() 設定作為此關聯反向關聯的關聯名稱。 yii\db\ActiveRelationTrait
join() 將 JOIN 部分附加到查詢。 yii\db\Query
joinWith() 與指定的關聯聯結。 yii\db\ActiveQuery
leftJoin() 將 LEFT OUTER JOIN 部分附加到查詢。 yii\db\Query
limit() 設定查詢的 LIMIT 部分。 yii\db\QueryTrait
max() 回傳指定欄位值的最大值。 yii\db\Query
min() 回傳指定欄位值的最小值。 yii\db\Query
noCache() 為此 Query 停用查詢快取。 yii\db\Query
off() 從此元件卸離現有的事件處理常式。 yii\base\Component
offset() 設定查詢的 OFFSET 部分。 yii\db\QueryTrait
on() 將事件處理常式附加到事件。 yii\base\Component
onCondition() 為關聯式查詢設定 ON 條件。 yii\db\ActiveQuery
one() 執行查詢並回傳單列結果。 yii\db\ActiveQuery
orFilterHaving() 將額外的 HAVING 條件新增到現有的條件,但忽略空運算元 yii\db\Query
orFilterWhere() 將額外的 WHERE 條件新增到現有的條件,但忽略空運算元 yii\db\QueryTrait
orHaving() 將額外的 HAVING 條件新增到現有的條件。 yii\db\Query
orOnCondition() 將額外的 ON 條件新增到現有的條件。 yii\db\ActiveQuery
orWhere() 將額外的 WHERE 條件新增到現有的條件。 yii\db\QueryTrait
orderBy() 設定查詢的 ORDER BY 部分。 yii\db\QueryTrait
params() 設定要繫結到查詢的參數。 yii\db\Query
populate() 將原始查詢結果轉換為此查詢指定的格式。 yii\db\ActiveQuery
populateRelation() 尋找相關記錄並將其填入主要模型。 yii\db\ActiveRelationTrait
prepare() 準備建構 SQL。 yii\db\ActiveQuery
rightJoin() 將 RIGHT OUTER JOIN 部分附加到查詢。 yii\db\Query
scalar() 以純量值形式回傳查詢結果。 yii\db\Query
select() 設定查詢的 SELECT 部分。 yii\db\Query
sum() 回傳指定欄位值的總和。 yii\db\Query
trigger() 觸發事件。 yii\base\Component
union() 使用 UNION 運算子附加 SQL 陳述式。 yii\db\Query
via() 指定與連接資料表相關聯的關聯。 yii\db\ActiveRelationTrait
viaTable() 為關聯式查詢指定連接資料表。 yii\db\ActiveQuery
where() 設定查詢的 WHERE 部分。 yii\db\QueryTrait
with() 指定應執行此查詢的關聯。 yii\db\ActiveQueryTrait
withQuery() 使用 WITH 語法預先加入 SQL 陳述式。 yii\db\Query

保護方法

隱藏繼承的方法

方法 描述 定義於
cleanUpTableNames() 清理資料表名稱和別名。別名和名稱都括在 {{ 和 }} 中。 yii\db\Query
createModels() 將找到的資料列轉換為模型實例。 yii\db\ActiveQueryTrait
filterCondition() 從給定的查詢條件中移除空運算元 yii\db\QueryTrait
getPrimaryTableName() yii\db\ActiveQuery
getTableNameAndAlias() 回傳 $modelClass 的資料表名稱和資料表別名。 yii\db\ActiveQuery
getUnaliasedColumnsFromSelect() yii\db\Query
getUniqueColumns() 回傳不重複的唯一欄位名稱。 yii\db\Query
isEmpty() 回傳一個值,指示給定值是否為「空」。 yii\db\QueryTrait
normalizeOrderBy() 正規化 ORDER BY 資料的格式。 yii\db\QueryTrait
normalizeSelect() 正規化傳遞給 select()addSelect() 的 SELECT 欄位。 yii\db\Query
queryScalar() 透過先設定 select() 來查詢純量值。 yii\db\ActiveQuery
setCommandCache() 如果此查詢已啟用快取,則設定 $command 快取。 yii\db\Query

事件

隱藏繼承的事件

事件 類型 描述 定義於
EVENT_INIT yii\db\Event 透過 init() 初始化查詢時觸發的事件。 yii\db\ActiveQuery

屬性詳細資訊

隱藏繼承的屬性

$joinWith 公開屬性

此查詢應聯結的關聯列表

public array|null $joinWith null
$on 公開屬性

當此查詢用於關聯內容時,要使用的聯結條件。當呼叫 yii\db\ActiveQuery::joinWith() 時,條件將用於 ON 部分。否則,條件將用於查詢的 WHERE 部分。請參閱 yii\db\Query::where(),以了解如何指定此參數。

另請參閱 onCondition()

public string|array|null $on null
$sql 公開屬性

要執行以檢索 AR 記錄的 SQL 陳述式。這由 yii\db\ActiveRecord::findBySql() 設定。

public string|null $sql null

方法詳細資訊

隱藏繼承的方法

__call() 公開方法

定義於: yii\base\Component::__call()

呼叫非類別方法的具名方法。

此方法將檢查是否有任何附加的行為具有具名方法,並在可用時執行它。

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當呼叫未知的方法時,將會隱含地呼叫它。

public mixed __call ( $name, $params )
$name string

方法名稱

$params array

方法參數

回傳 mixed

方法回傳值

拋出 yii\base\UnknownMethodException

當呼叫未知方法時

                public function __call($name, $params)
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $object) {
        if ($object->hasMethod($name)) {
            return call_user_func_array([$object, $name], $params);
        }
    }
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__clone() 公開方法

定義於: yii\db\ActiveRelationTrait::__clone()

複製內部物件。

public void __clone ( )

                public function __clone()
{
    parent::__clone();
    // make a clone of "via" object so that the same query object can be reused multiple times
    if (is_object($this->via)) {
        $this->via = clone $this->via;
    } elseif (is_array($this->via)) {
        $this->via = [$this->via[0], clone $this->via[1], $this->via[2]];
    }
}

            
__construct() 公開方法

建構子。

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

與此查詢相關聯的模型類別

$config array

要套用於新建立的查詢物件的組態

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

            
__get() 公開方法

定義於: yii\base\Component::__get()

回傳元件屬性的值。

此方法將依以下順序檢查並採取相應措施

  • getter 定義的屬性:回傳 getter 結果
  • 行為的屬性:回傳行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $value = $component->property; 時,將會隱含地呼叫它。

另請參閱 __set()

public mixed __get ( $name )
$name string

屬性名稱

回傳 mixed

屬性值或行為的屬性值

拋出 yii\base\UnknownPropertyException

如果未定義屬性

拋出 yii\base\InvalidCallException

如果屬性為唯寫。

                public function __get($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        // read property, e.g. getName()
        return $this->$getter();
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name;
        }
    }
    if (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() 公開方法

定義於: yii\base\Component::__isset()

檢查是否已設定屬性,即已定義且非 null。

此方法將依以下順序檢查並採取相應措施

  • setter 定義的屬性:回傳屬性是否已設定
  • 行為的屬性:回傳屬性是否已設定
  • 對於不存在的屬性回傳 false

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property) 時,將會隱含地呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.isset.php

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

回傳 布林值

具名屬性是否已設定

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canGetProperty($name)) {
            return $behavior->$name !== null;
        }
    }
    return false;
}

            
__set() 公開方法

定義於: yii\base\Component::__set()

設定元件屬性的值。

此方法將依以下順序檢查並採取相應措施

  • setter 定義的屬性:設定屬性值
  • 格式為 "on xyz" 的事件:將處理常式附加到事件 "xyz"
  • 格式為 "as xyz" 的行為:附加名為 "xyz" 的行為
  • 行為的屬性:設定行為屬性值

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 $component->property = $value; 時,將會隱含地呼叫它。

另請參閱 __get()

public void __set ( $name, $value )
$name string

屬性名稱或事件名稱

$value mixed

屬性值

拋出 yii\base\UnknownPropertyException

如果未定義屬性

拋出 yii\base\InvalidCallException

如果屬性為唯讀。

                public function __set($name, $value)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        // set property
        $this->$setter($value);
        return;
    } elseif (strncmp($name, 'on ', 3) === 0) {
        // on event: attach event handler
        $this->on(trim(substr($name, 3)), $value);
        return;
    } elseif (strncmp($name, 'as ', 3) === 0) {
        // as behavior: attach behavior
        $name = trim(substr($name, 3));
        $this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = $value;
            return;
        }
    }
    if (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}

            
__toString() 公開方法

定義於: yii\db\Query::__toString()

回傳 Query 的 SQL 表示法

public string __toString ( )

                public function __toString()
{
    return serialize($this);
}

            
__unset() 公開方法

定義於: yii\base\Component::__unset()

將元件屬性設定為 null。

此方法將依以下順序檢查並採取相應措施

  • setter 定義的屬性:將屬性值設定為 null
  • 行為的屬性:將屬性值設定為 null

請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property) 時,將會隱含地呼叫它。

另請參閱 https://php.dev.org.tw/manual/en/function.unset.php

public void __unset ( $name )
$name string

屬性名稱

拋出 yii\base\InvalidCallException

如果屬性為唯讀。

                public function __unset($name)
{
    $setter = 'set' . $name;
    if (method_exists($this, $setter)) {
        $this->$setter(null);
        return;
    }
    // behavior property
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $behavior) {
        if ($behavior->canSetProperty($name)) {
            $behavior->$name = null;
            return;
        }
    }
    throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}

            
addGroupBy() 公開方法

定義於: yii\db\Query::addGroupBy()

將額外的 group-by 欄位新增到現有的欄位。

另請參閱 groupBy()

public $this addGroupBy ( $columns )
$columns string|array|yii\db\ExpressionInterface

要分組的額外欄位。欄位可以使用字串 (例如 "id, name") 或陣列 (例如 ['id', 'name']) 指定。除非欄位包含一些括號 (表示欄位包含 DB 運算式),否則此方法將自動引用欄位名稱。

請注意,如果您的 group-by 是包含逗號的運算式,您應始終使用陣列來表示 group-by 資訊。否則,此方法將無法正確判斷 group-by 欄位。

自 2.0.7 版起,可以傳遞 yii\db\Expression 物件,以純 SQL 顯式指定 GROUP BY 部分。自 2.0.14 版起,也可以傳遞 yii\db\ExpressionInterface 物件。

回傳 $this

查詢物件本身

                public function addGroupBy($columns)
{
    if ($columns instanceof ExpressionInterface) {
        $columns = [$columns];
    } elseif (!is_array($columns)) {
        $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
    }
    if ($this->groupBy === null) {
        $this->groupBy = $columns;
    } else {
        $this->groupBy = array_merge($this->groupBy, $columns);
    }
    return $this;
}

            
addOrderBy() 公開方法

定義於: yii\db\QueryTrait::addOrderBy()

將額外的 ORDER BY 欄位新增到查詢中。

另請參閱 orderBy()

public $this addOrderBy ( $columns )
$columns string|array|yii\db\ExpressionInterface

要排序的欄位 (和方向)。欄位可以使用字串 (例如 "id ASC, name DESC") 或陣列 (例如 ['id' => SORT_ASC, 'name' => SORT_DESC]) 指定。

除非欄位包含一些括號 (表示欄位包含 DB 運算式),否則此方法將自動引用欄位名稱。

請注意,如果您的 order-by 是包含逗號的運算式,您應始終使用陣列來表示 order-by 資訊。否則,此方法將無法正確判斷 order-by 欄位。

自 2.0.7 版起,可以傳遞 yii\db\ExpressionInterface 物件,以純 SQL 顯式指定 ORDER BY 部分。

回傳 $this

查詢物件本身

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

            
addParams() 公開方法

定義於: yii\db\Query::addParams()

新增要繫結到查詢的額外參數。

另請參閱 params()

public $this addParams ( $params )
$params array

依參數預留位置索引的查詢參數值列表。例如,[':name' => 'Dan', ':age' => 31]

回傳 $this

查詢物件本身

                public function addParams($params)
{
    if (!empty($params)) {
        if (empty($this->params)) {
            $this->params = $params;
        } else {
            foreach ($params as $name => $value) {
                if (is_int($name)) {
                    $this->params[] = $value;
                } else {
                    $this->params[$name] = $value;
                }
            }
        }
    }
    return $this;
}

            
addSelect() 公開方法

定義於: yii\db\Query::addSelect()

將更多欄位新增到查詢的 SELECT 部分。

請注意,如果在之前未指定 select(),如果您也想選取所有剩餘的欄位,則應明確包含 *

$query->addSelect(["*", "CONCAT(first_name, ' ', last_name) AS full_name"])->one();

另請參閱 select()

public $this addSelect ( $columns )
$columns string|array|yii\db\ExpressionInterface

要新增到 select 的欄位。請參閱 select() 以取得有關此參數格式的更多詳細資訊。

回傳 $this

查詢物件本身

                public function addSelect($columns)
{
    if ($this->select === null) {
        return $this->select($columns);
    }
    if (!is_array($this->select)) {
        $this->select = $this->normalizeSelect($this->select);
    }
    $this->select = array_merge($this->select, $this->normalizeSelect($columns));
    return $this;
}

            
alias() 公開方法 (自 2.0.7 版起可用)

$modelClass 中定義的資料表定義別名。

此方法將調整 from(),以便覆寫已定義的別名。如果未定義別名,則將使用給定的別名填入 from()

public $this alias ( $alias )
$alias string

資料表別名。

回傳 $this

查詢物件本身

                public function alias($alias)
{
    if (empty($this->from) || count($this->from) < 2) {
        list($tableName) = $this->getTableNameAndAlias();
        $this->from = [$alias => $tableName];
    } else {
        $tableName = $this->getPrimaryTableName();
        foreach ($this->from as $key => $table) {
            if ($table === $tableName) {
                unset($this->from[$key]);
                $this->from[$alias] = $tableName;
            }
        }
    }
    return $this;
}

            
all() 公開方法

執行查詢並以陣列形式回傳所有結果。

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

用於建立 DB 命令的 DB 連線。如果為 null,將使用 $modelClass 回傳的 DB 連線。

回傳 array|yii\db\ActiveRecord[]

查詢結果。如果查詢結果為空,將回傳空陣列。

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

            
andFilterCompare() 公開方法 (自 2.0.8 版起可用)

定義於: yii\db\Query::andFilterCompare()

為特定欄位新增篩選條件,並允許使用者選擇篩選運算子。

它為給定的欄位新增額外的 WHERE 條件,並根據給定值的前幾個字元判斷比較運算子。條件的加入方式與 andFilterWhere() 相同,因此會忽略空值。新的條件和現有的條件將使用 AND 運算子聯結。

比較運算子會根據給定值中的前幾個字元智慧地判斷。特別是,如果以下運算子作為給定值中的前導字元出現,則會識別它們

  • <:欄位必須小於給定值。
  • >:欄位必須大於給定值。
  • <=:欄位必須小於或等於給定值。
  • >=:欄位必須大於或等於給定值。
  • <>:欄位不得與給定值相同。
  • =:欄位必須等於給定值。
  • 如果未偵測到上述任何運算子,將使用 $defaultOperator
public $this andFilterCompare ( $name, $value, $defaultOperator '=' )
$name string

欄位名稱。

$value string

欄位值,可選擇性地在其前面加上比較運算子。

$defaultOperator string

$value 中未給定運算子時使用的運算子。預設為 =,執行精確匹配。

回傳 $this

查詢物件本身

                public function andFilterCompare($name, $value, $defaultOperator = '=')
{
    if (preg_match('/^(<>|>=|>|<=|<|=)/', (string)$value, $matches)) {
        $operator = $matches[1];
        $value = substr($value, strlen($operator));
    } else {
        $operator = $defaultOperator;
    }
    return $this->andFilterWhere([$operator, $name, $value]);
}

            
andFilterHaving() public method (available since version 2.0.11)

Defined in: yii\db\Query::andFilterHaving()

將額外的 HAVING 條件新增到現有的條件,但忽略空運算元

新的條件會使用 AND 運算子與現有條件結合。

此方法與 andHaving() 相似。主要區別在於此方法會移除 空的查詢運算元。因此,此方法最適合用於根據使用者輸入的篩選值來建立查詢條件。

參見

public $this andFilterHaving ( array $condition )
$condition array

新的 HAVING 條件。請參考 having() 以了解如何指定此參數。

回傳 $this

查詢物件本身

                public function andFilterHaving(array $condition)
{
    $condition = $this->filterCondition($condition);
    if ($condition !== []) {
        $this->andHaving($condition);
    }
    return $this;
}

            
andFilterWhere() public method

Defined in: yii\db\QueryTrait::andFilterWhere()

將額外的 WHERE 條件新增到現有的條件,但忽略空運算元

新的條件會使用 'AND' 運算子與現有條件結合。

此方法與 andWhere() 相似。主要區別在於此方法會移除 空的查詢運算元。因此,此方法最適合用於根據使用者輸入的篩選值來建立查詢條件。

參見

public $this andFilterWhere ( array $condition )
$condition array

新的 WHERE 條件。請參考 where() 以了解如何指定此參數。

回傳 $this

查詢物件本身

                public function andFilterWhere(array $condition)
{
    $condition = $this->filterCondition($condition);
    if ($condition !== []) {
        $this->andWhere($condition);
    }
    return $this;
}

            
andHaving() public method

Defined in: yii\db\Query::andHaving()

將額外的 HAVING 條件新增到現有的條件。

新的條件會使用 AND 運算子與現有條件結合。

參見

public $this andHaving ( $condition, $params = [] )
$condition string|array|yii\db\ExpressionInterface

新的 HAVING 條件。請參考 where() 以了解如何指定此參數。

$params array

要綁定到查詢的參數 (name => value)。

回傳 $this

查詢物件本身

                public function andHaving($condition, $params = [])
{
    if ($this->having === null) {
        $this->having = $condition;
    } else {
        $this->having = ['and', $this->having, $condition];
    }
    $this->addParams($params);
    return $this;
}

            
andOnCondition() public method

將額外的 ON 條件新增到現有的條件。

新的條件會使用 'AND' 運算子與現有條件結合。

參見

public $this andOnCondition ( $condition, $params = [] )
$condition string|array

新的 ON 條件。請參考 where() 以了解如何指定此參數。

$params array

要綁定到查詢的參數 (name => value)。

回傳 $this

查詢物件本身

                public function andOnCondition($condition, $params = [])
{
    if ($this->on === null) {
        $this->on = $condition;
    } else {
        $this->on = ['and', $this->on, $condition];
    }
    $this->addParams($params);
    return $this;
}

            
andWhere() public method

Defined in: yii\db\QueryTrait::andWhere()

將額外的 WHERE 條件新增到現有的條件。

新的條件會使用 'AND' 運算子與現有條件結合。

參見

public $this andWhere ( $condition )
$condition string|array|yii\db\ExpressionInterface

新的 WHERE 條件。請參考 where() 以了解如何指定此參數。

回傳 $this

查詢物件本身

                public function andWhere($condition)
{
    if ($this->where === null) {
        $this->where = $condition;
    } else {
        $this->where = ['and', $this->where, $condition];
    }
    return $this;
}

            
asArray() public method

Defined in: yii\db\ActiveQueryTrait::asArray()

設定 asArray() 屬性。

public $this asArray ( $value true )
$value 布林值

是否以陣列而非 Active Record 的形式傳回查詢結果。

回傳 $this

查詢物件本身

                public function asArray($value = true)
{
    $this->asArray = $value;
    return $this;
}

            
attachBehavior() public method

Defined in: yii\base\Component::attachBehavior()

將行為附加到此元件。

此方法會根據給定的配置建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法將行為物件附加到此元件。

參見 detachBehavior()

public yii\base\Behavior attachBehavior ( $name, $behavior )
$name string

行為的名稱。

$behavior string|array|yii\base\Behavior

行為配置。可以是下列其中之一

回傳 yii\base\Behavior

行為物件

                public function attachBehavior($name, $behavior)
{
    $this->ensureBehaviors();
    return $this->attachBehaviorInternal($name, $behavior);
}

            
attachBehaviors() public method

Defined in: yii\base\Component::attachBehaviors()

將行為列表附加到元件。

每個行為都依其名稱編製索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串或用於建立行為的配置陣列。

參見 attachBehavior()

public void attachBehaviors ( $behaviors )
$behaviors array

要附加到元件的行為列表

                public function attachBehaviors($behaviors)
{
    $this->ensureBehaviors();
    foreach ($behaviors as $name => $behavior) {
        $this->attachBehaviorInternal($name, $behavior);
    }
}

            
average() public method

Defined in: yii\db\Query::average()

回傳指定欄位值的平均值。

public mixed average ( $q, $db null )
$q string

欄位名稱或運算式。請確保您已正確地 引用 運算式中的欄位名稱。

$db yii\db\Connection|null

用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 db 應用程式元件。

回傳 mixed

指定欄位值的平均值。

                public function average($q, $db = null)
{
    if ($this->emulateExecution) {
        return 0;
    }
    return $this->queryScalar("AVG($q)", $db);
}

            
batch() public method

Defined in: yii\db\Query::batch()

開始批次查詢。

批次查詢支援以批次方式提取資料,這可以將記憶體使用量保持在限制之下。此方法將傳回 yii\db\BatchQueryResult 物件,該物件實作了 Iterator 介面,並且可以遍歷以批次方式檢索資料。

例如,

$query = (new Query)->from('user');
foreach ($query->batch() as $rows) {
    // $rows is an array of 100 or fewer rows from user table
}
public yii\db\BatchQueryResult batch ( $batchSize 100, $db null )
$batchSize integer

每個批次中要提取的記錄數。

$db yii\db\Connection|null

資料庫連線。如果未設定,將使用 "db" 應用程式元件。

回傳 yii\db\BatchQueryResult

批次查詢結果。它實作了 Iterator 介面,並且可以遍歷以批次方式檢索資料。

                public function batch($batchSize = 100, $db = null)
{
    return Yii::createObject([
        'class' => BatchQueryResult::className(),
        'query' => $this,
        'batchSize' => $batchSize,
        'db' => $db,
        'each' => false,
    ]);
}

            
behaviors() public method

Defined in: yii\base\Component::behaviors()

回傳此元件應表現為的行為列表。

子類別可以覆寫此方法以指定它們想要表現為的行為。

此方法的傳回值應該是行為物件或配置的陣列,並以行為名稱編製索引。行為配置可以是指定行為類別的字串,也可以是以下結構的陣列

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

請注意,行為類別必須從 yii\base\Behavior 擴展。行為可以使用名稱或匿名方式附加。當名稱用作陣列索引鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。

在此方法中宣告的行為將自動(按需)附加到元件。

public array behaviors ( )
回傳 array

行為配置。

                public function behaviors()
{
    return [];
}

            
cache() public method (available since version 2.0.14)

Defined in: yii\db\Query::cache()

為此 Query 啟用查詢快取。

public $this cache ( $duration true, $dependency null )
$duration integer|true

查詢結果在快取中保持有效的秒數。使用 0 表示快取資料永遠不會過期。使用負數表示不應使用查詢快取。使用布林值 true 表示應使用 yii\db\Connection::$queryCacheDuration。預設為 true

$dependency yii\caching\Dependency|null

與快取結果相關聯的快取相依性。

回傳 $this

Query 物件本身

                public function cache($duration = true, $dependency = null)
{
    $this->queryCacheDuration = $duration;
    $this->queryCacheDependency = $dependency;
    return $this;
}

            
canGetProperty() public method

Defined in: yii\base\Component::canGetProperty()

回傳一個值,指示是否可以讀取屬性。

如果滿足以下條件,則可以讀取屬性

  • 類別具有與指定名稱關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可讀屬性(當 $checkBehaviors 為 true 時)。

參見 canSetProperty()

public boolean canGetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

是否將行為的屬性視為此元件的屬性

回傳 布林值

屬性是否可以讀取

                public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canGetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
canSetProperty() public method

Defined in: yii\base\Component::canSetProperty()

回傳一個值,指示是否可以設定屬性。

如果滿足以下條件,則可以寫入屬性

  • 類別具有與指定名稱關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的可寫屬性(當 $checkBehaviors 為 true 時)。

參見 canGetProperty()

public boolean canSetProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

是否將行為的屬性視為此元件的屬性

回傳 布林值

屬性是否可以寫入

                public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
    if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->canSetProperty($name, $checkVars)) {
                return true;
            }
        }
    }
    return false;
}

            
className() public static method
Deprecated since 2.0.14. On PHP >=5.5, use ::class instead.

Defined in: yii\base\BaseObject::className()

回傳此類別的完整命名空間名稱。

public static string className ( )
回傳 string

此類別的完整限定名稱。

                public static function className()
{
    return get_called_class();
}

            
cleanUpTableNames() protected method (available since version 2.0.14)

Defined in: yii\db\Query::cleanUpTableNames()

清理資料表名稱和別名。別名和名稱都括在 {{ 和 }} 中。

protected string[] cleanUpTableNames ( $tableNames )
$tableNames array

非空陣列

回傳 string[]

以別名編製索引的表名稱

                protected function cleanUpTableNames($tableNames)
{
    $cleanedUpTableNames = [];
    foreach ($tableNames as $alias => $tableName) {
        if (is_string($tableName) && !is_string($alias)) {
            $pattern = <<<PATTERN
'"`\[]|{{)
'"`\]]|}})
?\)
\s+
(?:as)?
\s*
?:['"`\[]|{{)
.*?
(?:['"`\]]|}})
|
.*?

ERN;
            if (preg_match($pattern, $tableName, $matches)) {
                if (isset($matches[2])) {
                    list(, $tableName, $alias) = $matches;
                } else {
                    $tableName = $alias = $matches[1];
                }
            }
        }
        if ($tableName instanceof Expression) {
            if (!is_string($alias)) {
                throw new InvalidArgumentException('To use Expression in from() method, pass it in array format with alias.');
            }
            $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
        } elseif ($tableName instanceof self) {
            $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $tableName;
        } else {
            $cleanedUpTableNames[$this->ensureNameQuoted($alias)] = $this->ensureNameQuoted($tableName);
        }
    }
    return $cleanedUpTableNames;
}

            
column() public method

Defined in: yii\db\Query::column()

執行查詢並回傳結果的第一個欄位。

public array column ( $db null )
$db yii\db\Connection|null

用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 db 應用程式元件。

回傳 array

查詢結果的第一個欄位。如果查詢沒有結果,則傳回空陣列。

                public function column($db = null)
{
    if ($this->emulateExecution) {
        return [];
    }
    if ($this->indexBy === null) {
        return $this->createCommand($db)->queryColumn();
    }
    if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
        if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
            $this->select[] = key($tables) . '.' . $this->indexBy;
        } else {
            $this->select[] = $this->indexBy;
        }
    }
    $rows = $this->createCommand($db)->queryAll();
    $results = [];
    $column = null;
    if (is_string($this->indexBy)) {
        if (($dotPos = strpos($this->indexBy, '.')) === false) {
            $column = $this->indexBy;
        } else {
            $column = substr($this->indexBy, $dotPos + 1);
        }
    }
    foreach ($rows as $row) {
        $value = reset($row);
        if ($this->indexBy instanceof \Closure) {
            $results[call_user_func($this->indexBy, $row)] = $value;
        } else {
            $results[$row[$column]] = $value;
        }
    }
    return $results;
}

            
count() public method

Defined in: yii\db\Query::count()

回傳記錄數。

public integer|string|null count ( $q '*', $db null )
$q string

COUNT 運算式。預設為 '*'。請確保您已正確地 引用 運算式中的欄位名稱。

$db yii\db\Connection|null

用於產生 SQL 陳述式的資料庫連線。如果未給定此參數(或為 null),將使用 db 應用程式元件。

回傳 integer|string|null

記錄數。結果可能是字串,具體取決於底層資料庫引擎,並且支援高於 32 位元 PHP 整數可以處理的整數值。

                public function count($q = '*', $db = null)
{
    if ($this->emulateExecution) {
        return 0;
    }
    return $this->queryScalar("COUNT($q)", $db);
}

            
create() public static method

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

建立新的 Query 物件,並從現有的物件複製其屬性值。

正在複製的屬性是查詢建構器要使用的屬性。

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

來源查詢物件

回傳 yii\db\Query

新的 Query 物件

                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,
        'withQueries' => $from->withQueries,
    ]);
}

            
createCommand() public method

建立可用於執行此查詢的 DB 命令。

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

用於建立 DB 命令的 DB 連線。如果為 null,將使用 $modelClass 傳回的 DB 連線。

回傳 yii\db\Command

建立的 DB 命令實例。

                public function createCommand($db = null)
{
    /* @var $modelClass ActiveRecord */
    $modelClass = $this->modelClass;
    if ($db === null) {
        $db = $modelClass::getDb();
    }
    if ($this->sql === null) {
        list($sql, $params) = $db->getQueryBuilder()->build($this);
    } else {
        $sql = $this->sql;
        $params = $this->params;
    }
    $command = $db->createCommand($sql, $params);
    $this->setCommandCache($command);
    return $command;
}

            
createModels() protected method (available since version 2.0.11)

Defined in: yii\db\ActiveQueryTrait::createModels()

將找到的資料列轉換為模型實例。

protected array|yii\db\ActiveRecord[] createModels ( $rows )
$rows array

                protected function createModels($rows)
{
    if ($this->asArray) {
        return $rows;
    } else {
        $models = [];
        /* @var $class ActiveRecord */
        $class = $this->modelClass;
        foreach ($rows as $row) {
            $model = $class::instantiate($row);
            $modelClass = get_class($model);
            $modelClass::populateRecord($model, $row);
            $models[] = $model;
        }
        return $models;
    }
}

            
detachBehavior() public method

Defined in: yii\base\Component::detachBehavior()

從元件卸離行為。

將會調用行為的 yii\base\Behavior::detach() 方法。

public yii\base\Behavior|null detachBehavior ( $name )
$name string

行為的名稱。

回傳 yii\base\Behavior|null

分離的行為。如果行為不存在,則為 Null。

                public function detachBehavior($name)
{
    $this->ensureBehaviors();
    if (isset($this->_behaviors[$name])) {
        $behavior = $this->_behaviors[$name];
        unset($this->_behaviors[$name]);
        $behavior->detach();
        return $behavior;
    }
    return null;
}

            
detachBehaviors() public method

Defined in: yii\base\Component::detachBehaviors()

從元件卸離所有行為。

public void detachBehaviors ( )

                public function detachBehaviors()
{
    $this->ensureBehaviors();
    foreach ($this->_behaviors as $name => $behavior) {
        $this->detachBehavior($name);
    }
}

            
distinct() public method

Defined in: yii\db\Query::distinct()

設定是否選取 DISTINCT 的值。

public $this distinct ( $value true )
$value 布林值

是否 SELECT DISTINCT。

回傳 $this

查詢物件本身

                public function distinct($value = true)
{
    $this->distinct = $value;
    return $this;
}

            
each() public method

Defined in: yii\db\Query::each()

開始批次查詢並逐列檢索資料。

此方法與 batch() 相似,不同之處在於在結果的每次迭代中,僅傳回一列資料。例如,

$query = (new Query)->from('user');
foreach ($query->each() as $row) {
}
public yii\db\BatchQueryResult each ( $batchSize 100, $db null )
$batchSize integer

每個批次中要提取的記錄數。

$db yii\db\Connection|null

資料庫連線。如果未設定,將使用 "db" 應用程式元件。

回傳 yii\db\BatchQueryResult

批次查詢結果。它實作了 Iterator 介面,並且可以遍歷以批次方式檢索資料。

                public function each($batchSize = 100, $db = null)
{
    return Yii::createObject([
        'class' => BatchQueryResult::className(),
        'query' => $this,
        'batchSize' => $batchSize,
        'db' => $db,
        'each' => true,
    ]);
}

            
emulateExecution() public method (available since version 2.0.11)

Defined in: yii\db\QueryTrait::emulateExecution()

設定是否模擬查詢執行,防止與資料儲存進行任何互動。

啟用此模式後,傳回查詢結果的方法,例如 yii\db\QueryInterface::one()yii\db\QueryInterface::all()yii\db\QueryInterface::exists() 等等,將傳回空值或 false 值。如果您的程式邏輯指示查詢不應傳回任何結果,例如在您設定 false where 條件(例如 0=1)的情況下,您應該使用此方法。

public $this emulateExecution ( $value true )
$value 布林值

是否阻止查詢執行。

回傳 $this

查詢物件本身。

                public function emulateExecution($value = true)
{
    $this->emulateExecution = $value;
    return $this;
}

            
ensureBehaviors() public method

Defined in: yii\base\Component::ensureBehaviors()

確保在 behaviors() 中宣告的行為已附加到此元件。

public void ensureBehaviors ( )

                public function ensureBehaviors()
{
    if ($this->_behaviors === null) {
        $this->_behaviors = [];
        foreach ($this->behaviors() as $name => $behavior) {
            $this->attachBehaviorInternal($name, $behavior);
        }
    }
}

            
exists() public method

定義於: yii\db\Query::exists()

回傳一個值,指示查詢結果是否包含任何資料列。

public boolean exists ( $db null )
$db yii\db\Connection|null

用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 db 應用程式元件。

回傳 布林值

查詢結果是否包含任何資料列。

                public function exists($db = null)
{
    if ($this->emulateExecution) {
        return false;
    }
    $command = $this->createCommand($db);
    $params = $command->params;
    $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
    $command->bindValues($params);
    return (bool) $command->queryScalar();
}

            
filterCondition() protected method

定義於: yii\db\QueryTrait::filterCondition()

從給定的查詢條件中移除空運算元

protected array filterCondition ( $condition )
$condition array

原始條件

回傳 array

已移除 空運算元 的條件。

拋出 yii\base\NotSupportedException

如果條件運算子不被支援

                protected function filterCondition($condition)
{
    if (!is_array($condition)) {
        return $condition;
    }
    if (!isset($condition[0])) {
        // hash format: 'column1' => 'value1', 'column2' => 'value2', ...
        foreach ($condition as $name => $value) {
            if ($this->isEmpty($value)) {
                unset($condition[$name]);
            }
        }
        return $condition;
    }
    // operator format: operator, operand 1, operand 2, ...
    $operator = array_shift($condition);
    switch (strtoupper($operator)) {
        case 'NOT':
        case 'AND':
        case 'OR':
            foreach ($condition as $i => $operand) {
                $subCondition = $this->filterCondition($operand);
                if ($this->isEmpty($subCondition)) {
                    unset($condition[$i]);
                } else {
                    $condition[$i] = $subCondition;
                }
            }
            if (empty($condition)) {
                return [];
            }
            break;
        case 'BETWEEN':
        case 'NOT BETWEEN':
            if (array_key_exists(1, $condition) && array_key_exists(2, $condition)) {
                if ($this->isEmpty($condition[1]) || $this->isEmpty($condition[2])) {
                    return [];
                }
            }
            break;
        default:
            if (array_key_exists(1, $condition) && $this->isEmpty($condition[1])) {
                return [];
            }
    }
    array_unshift($condition, $operator);
    return $condition;
}

            
filterHaving() public method (自版本 2.0.11 起可用)

定義於: yii\db\Query::filterHaving()

設定查詢的 HAVING 部分,但忽略空運算元

此方法與 having() 相似。主要區別在於此方法會移除 空的查詢運算元。因此,此方法最適合基於使用者輸入的篩選值來建立查詢條件。

以下程式碼展示此方法與 having() 之間的差異

// HAVING `age`=:age
$query->filterHaving(['name' => null, 'age' => 20]);
// HAVING `age`=:age
$query->having(['age' => 20]);
// HAVING `name` IS NULL AND `age`=:age
$query->having(['name' => null, 'age' => 20]);

請注意,與 having() 不同,您不能將繫結參數傳遞給此方法。

參見

public $this filterHaving ( array $condition )
$condition array

應放置在 HAVING 部分的條件。請參閱 having() 以了解如何指定此參數。

回傳 $this

查詢物件本身

                public function filterHaving(array $condition)
{
    $condition = $this->filterCondition($condition);
    if ($condition !== []) {
        $this->having($condition);
    }
    return $this;
}

            
filterWhere() public method

定義於: yii\db\QueryTrait::filterWhere()

設定查詢的 WHERE 部分,但忽略空運算元

此方法與 where() 相似。主要區別在於此方法會移除 空的查詢運算元。因此,此方法最適合基於使用者輸入的篩選值來建立查詢條件。

以下程式碼展示此方法與 where() 之間的差異

// WHERE `age`=:age
$query->filterWhere(['name' => null, 'age' => 20]);
// WHERE `age`=:age
$query->where(['age' => 20]);
// WHERE `name` IS NULL AND `age`=:age
$query->where(['name' => null, 'age' => 20]);

請注意,與 where() 不同,您不能將繫結參數傳遞給此方法。

參見

public $this filterWhere ( array $condition )
$condition array

應放置在 WHERE 部分的條件。請參閱 where() 以了解如何指定此參數。

回傳 $this

查詢物件本身

                public function filterWhere(array $condition)
{
    $condition = $this->filterCondition($condition);
    if ($condition !== []) {
        $this->where($condition);
    }
    return $this;
}

            
findFor() public method

定義於: yii\db\ActiveRelationTrait::findFor()

尋找指定主要記錄的相關記錄。

當以延遲方式存取 ActiveRecord 的關聯時,會調用此方法。

public mixed findFor ( $name, $model )
$name string

關聯名稱

$model yii\db\ActiveRecordInterface|yii\db\BaseActiveRecord

主要模型

回傳 mixed

相關的記錄

拋出 yii\base\InvalidArgumentException

如果關聯無效

                public function findFor($name, $model)
{
    if (method_exists($model, 'get' . $name)) {
        $method = new \ReflectionMethod($model, 'get' . $name);
        $realName = lcfirst(substr($method->getName(), 3));
        if ($realName !== $name) {
            throw new InvalidArgumentException('Relation names are case sensitive. ' . get_class($model) . " has a relation named \"$realName\" instead of \"$name\".");
        }
    }
    return $this->multiple ? $this->all() : $this->one();
}

            
findWith() public method

定義於: yii\db\ActiveQueryTrait::findWith()

尋找對應於一個或多個關聯的記錄,並將其填入主要模型。

public void findWith ( $with, &$models )
$with array

此查詢應執行的關聯列表。 有關指定此參數的詳細資訊,請參閱 with()

$models array|yii\db\ActiveRecord[]

主要模型(可以是 AR 實例或陣列)

                public function findWith($with, &$models)
{
    if (empty($models)) {
        return;
    }
    $primaryModel = reset($models);
    if (!$primaryModel instanceof ActiveRecordInterface) {
        /* @var $modelClass ActiveRecordInterface */
        $modelClass = $this->modelClass;
        $primaryModel = $modelClass::instance();
    }
    $relations = $this->normalizeRelations($primaryModel, $with);
    /* @var $relation ActiveQuery */
    foreach ($relations as $name => $relation) {
        if ($relation->asArray === null) {
            // inherit asArray from primary query
            $relation->asArray($this->asArray);
        }
        $relation->populateRelation($name, $models);
    }
}

            
from() public method

定義於: yii\db\Query::from()

設定查詢的 FROM 部分。

public $this from ( $tables )
$tables string|array|yii\db\ExpressionInterface

要從中選取的資料表。 這可以是字串 (例如 'user') 或陣列 (例如 ['user', 'profile']),指定一個或多個資料表名稱。 資料表名稱可以包含結構描述前綴 (例如 'public.user') 和/或資料表別名 (例如 'user u')。 除非資料表名稱包含括號(表示資料表以子查詢或 DB 運算式給出),否則此方法將自動引用資料表名稱。

當資料表指定為陣列時,您也可以使用陣列鍵作為資料表別名(如果資料表不需要別名,請勿使用字串鍵)。

使用 Query 物件來表示子查詢。 在這種情況下,對應的陣列鍵將用作子查詢的別名。

若要以純 SQL 指定 FROM 部分,您可以傳遞 yii\db\ExpressionInterface 的實例。

以下是一些範例

// SELECT * FROM  `user` `u`, `profile`;
$query = (new \yii\db\Query)->from(['u' => 'user', 'profile']);

// SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
$subquery = (new \yii\db\Query)->from('user')->where(['active' => true])
$query = (new \yii\db\Query)->from(['activeusers' => $subquery]);

// subquery can also be a string with plain SQL wrapped in parenthesis
// SELECT * FROM (SELECT * FROM `user` WHERE `active` = 1) `activeusers`;
$subquery = "(SELECT * FROM `user` WHERE `active` = 1)";
$query = (new \yii\db\Query)->from(['activeusers' => $subquery]);
回傳 $this

查詢物件本身

                public function from($tables)
{
    if ($tables instanceof ExpressionInterface) {
        $tables = [$tables];
    }
    if (is_string($tables)) {
        $tables = preg_split('/\s*,\s*/', trim($tables), -1, PREG_SPLIT_NO_EMPTY);
    }
    $this->from = $tables;
    return $this;
}

            
getBehavior() public method

定義於: yii\base\Component::getBehavior()

回傳具名的行為物件。

public yii\base\Behavior|null getBehavior ( $name )
$name string

行為名稱

回傳 yii\base\Behavior|null

行為物件,如果行為不存在則為 null

                public function getBehavior($name)
{
    $this->ensureBehaviors();
    return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}

            
getBehaviors() public method

定義於: yii\base\Component::getBehaviors()

回傳附加到此元件的所有行為。

public yii\base\Behavior[] getBehaviors ( )
回傳 yii\base\Behavior[]

附加到此元件的行為列表

                public function getBehaviors()
{
    $this->ensureBehaviors();
    return $this->_behaviors;
}

            
getPrimaryTableName() protected method (自版本 2.0.12 起可用)

protected string getPrimaryTableName ( )
回傳 string

主要資料表名稱

                protected function getPrimaryTableName()
{
    /* @var $modelClass ActiveRecord */
    $modelClass = $this->modelClass;
    return $modelClass::tableName();
}

            
getTableNameAndAlias() protected method (自版本 2.0.16 起可用)

回傳 $modelClass 的資料表名稱和資料表別名。

定義於: yii\db\ActiveQuery::getTableNameAndAlias()
回傳 array

protected array getTableNameAndAlias ( )

                protected function getTableNameAndAlias()
{
    if (empty($this->from)) {
        $tableName = $this->getPrimaryTableName();
    } else {
        $tableName = '';
        // if the first entry in "from" is an alias-tablename-pair return it directly
        foreach ($this->from as $alias => $tableName) {
            if (is_string($alias)) {
                return [$tableName, $alias];
            }
            break;
        }
    }
    if (preg_match('/^(.*?)\s+({{\w+}}|\w+)$/', $tableName, $matches)) {
        $alias = $matches[2];
    } else {
        $alias = $tableName;
    }
    return [$tableName, $alias];
}

            
資料表名稱和資料表別名。

回傳在 from() 中使用的資料表名稱,依別名索引。

getTablesUsedInFrom() public method (自版本 2.0.12 起可用)

public string[] getTablesUsedInFrom ( )
回傳 string[]

以別名編製索引的表名稱

拋出 yii\base\InvalidConfigException

                public function getTablesUsedInFrom()
{
    if (empty($this->from)) {
        return $this->cleanUpTableNames([$this->getPrimaryTableName()]);
    }
    return parent::getTablesUsedInFrom();
}

            
getUnaliasedColumnsFromSelect() protected method (自版本 2.0.14 起可用)
在 2.0.21 版本中已過時
protected array getUnaliasedColumnsFromSelect ( )
回傳 array

來自 SELECT 語句的無別名欄位列表。

                protected function getUnaliasedColumnsFromSelect()
{
    $result = [];
    if (is_array($this->select)) {
        foreach ($this->select as $name => $value) {
            if (is_int($name)) {
                $result[] = $value;
            }
        }
    }
    return array_unique($result);
}

            
getUniqueColumns() protected method (自版本 2.0.14 起可用)
在 2.0.21 版本中已過時

定義於: yii\db\Query::getUniqueColumns()

回傳不重複的唯一欄位名稱。

要移除的欄位

  • 如果欄位定義已存在於 SELECT 部分,且具有相同的別名
  • 如果沒有別名的欄位定義也已經存在於 SELECT 部分,且同樣沒有別名
protected void getUniqueColumns ( $columns )
$columns array

要合併到 select 中的欄位。

                protected function getUniqueColumns($columns)
{
    $unaliasedColumns = $this->getUnaliasedColumnsFromSelect();
    $result = [];
    foreach ($columns as $columnAlias => $columnDefinition) {
        if (!$columnDefinition instanceof Query) {
            if (is_string($columnAlias)) {
                $existsInSelect = isset($this->select[$columnAlias]) && $this->select[$columnAlias] === $columnDefinition;
                if ($existsInSelect) {
                    continue;
                }
            } elseif (is_int($columnAlias)) {
                $existsInSelect = in_array($columnDefinition, $unaliasedColumns, true);
                $existsInResultSet = in_array($columnDefinition, $result, true);
                if ($existsInSelect || $existsInResultSet) {
                    continue;
                }
            }
        }
        $result[$columnAlias] = $columnDefinition;
    }
    return $result;
}

            
groupBy() public method

定義於: yii\db\Query::groupBy()

設定查詢的 GROUP BY 部分。

另請參閱 addGroupBy()

public $this groupBy ( $columns )
$columns string|array|yii\db\ExpressionInterface|null

要分組依據的欄位。 欄位可以字串 (例如 "id, name") 或陣列 (例如 ['id', 'name']) 形式指定。 除非欄位包含括號(表示欄位包含 DB 運算式),否則此方法將自動引用欄位名稱。

請注意,如果您的 group-by 是包含逗號的運算式,您應始終使用陣列來表示 group-by 資訊。否則,此方法將無法正確判斷 group-by 欄位。

自 2.0.7 版起,可以傳遞 yii\db\ExpressionInterface 物件,以純 SQL 明確指定 GROUP BY 部分。 自 2.0.14 版起,也可以傳遞 yii\db\ExpressionInterface 物件。

回傳 $this

查詢物件本身

                public function groupBy($columns)
{
    if ($columns instanceof ExpressionInterface) {
        $columns = [$columns];
    } elseif (!is_array($columns) && !is_null($columns)) {
        $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
    }
    $this->groupBy = $columns;
    return $this;
}

            
hasEventHandlers() public method

定義於: yii\base\Component::hasEventHandlers()

回傳一個值,指示是否有名稱事件附加任何處理常式。

public boolean hasEventHandlers ( $name )
$name string

事件名稱

回傳 布林值

是否有任何處理常式附加到事件。

                public function hasEventHandlers($name)
{
    $this->ensureBehaviors();
    if (!empty($this->_events[$name])) {
        return true;
    }
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
            return true;
        }
    }
    return Event::hasHandlers($this, $name);
}

            
hasMethod() public method

定義於: yii\base\Component::hasMethod()

回傳一個值,指示是否已定義方法。

如果滿足以下條件,則定義方法

  • 類別具有指定名稱的方法
  • 附加的行為具有給定名稱的方法(當 $checkBehaviors 為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors true )
$name string

屬性名稱

$checkBehaviors 布林值

是否將行為的方法視為此元件的方法

回傳 布林值

方法是否已定義

                public function hasMethod($name, $checkBehaviors = true)
{
    if (method_exists($this, $name)) {
        return true;
    } elseif ($checkBehaviors) {
        $this->ensureBehaviors();
        foreach ($this->_behaviors as $behavior) {
            if ($behavior->hasMethod($name)) {
                return true;
            }
        }
    }
    return false;
}

            
hasProperty() public method

定義於: yii\base\Component::hasProperty()

回傳一個值,指示是否為此元件定義了屬性。

如果滿足以下條件,則定義屬性

  • 類別具有與指定名稱相關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
  • 類別具有具有指定名稱的成員變數(當 $checkVars 為 true 時);
  • 附加的行為具有給定名稱的屬性(當 $checkBehaviors 為 true 時)。

參見

public boolean hasProperty ( $name, $checkVars true, $checkBehaviors true )
$name string

屬性名稱

$checkVars 布林值

是否將成員變數視為屬性

$checkBehaviors 布林值

是否將行為的屬性視為此元件的屬性

回傳 布林值

屬性是否已定義

                public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
    return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}

            
having() public method

定義於: yii\db\Query::having()

設定查詢的 HAVING 部分。

參見

public $this having ( $condition, $params = [] )
$condition string|array|yii\db\ExpressionInterface

要放在 HAVING 後面的條件。 請參閱 where() 以了解如何指定此參數。

$params array

要綁定到查詢的參數 (name => value)。

回傳 $this

查詢物件本身

                public function having($condition, $params = [])
{
    $this->having = $condition;
    $this->addParams($params);
    return $this;
}

            
indexBy() public method

定義於: yii\db\QueryTrait::indexBy()

設定 indexBy() 屬性。

public $this indexBy ( $column )
$column string|callable

應依其索引查詢結果的欄位名稱。 這也可以是一個可調用項(例如匿名函數),它根據給定的資料列資料傳回索引值。 可調用項的簽章應為

function ($row)
{
    // return the index value corresponding to $row
}
回傳 $this

查詢物件本身

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

            
init() public method

初始化物件。

此方法在建構函式的末尾調用。 預設實作將觸發 EVENT_INIT 事件。 如果您覆寫此方法,請確保在結尾調用父實作,以確保觸發事件。

public void init ( )

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

            
innerJoin() public method

定義於: yii\db\Query::innerJoin()

將 INNER JOIN 部分附加到查詢。

public $this innerJoin ( $table, $on '', $params = [] )
$table string|array

要聯結的資料表或子查詢。

使用字串來表示要聯結的資料表名稱。 資料表名稱可以包含結構描述前綴 (例如 'public.user') 和/或資料表別名 (例如 'user u')。 除非資料表名稱包含括號(表示資料表以子查詢或 DB 運算式給出),否則此方法將自動引用資料表名稱。

您也可以將資料表指定為具有一個元素的陣列,並使用陣列鍵作為資料表別名(例如 ['u' => 'user'])。

若要聯結子查詢,請使用具有一個元素的陣列,值設定為表示子查詢的 yii\db\Query 物件,且對應的鍵表示別名。

$on string|array

應出現在 ON 部分的聯結條件。 有關如何指定此參數,請參閱 join()

$params array

要綁定到查詢的參數 (name => value)。

回傳 $this

查詢物件本身

                public function innerJoin($table, $on = '', $params = [])
{
    $this->join[] = ['INNER JOIN', $table, $on];
    return $this->addParams($params);
}

            
innerJoinWith() public method

與指定的關聯進行內部聯結。

這是 joinWith() 的快捷方法,聯結類型設定為 "INNER JOIN"。 有關此方法的詳細用法,請參閱 joinWith()

另請參閱 joinWith()

public $this innerJoinWith ( $with, $eagerLoading true )
$with string|array

要聯結的關聯。

$eagerLoading boolean|array

是否預先載入關聯。 請注意,這並不表示關聯是從查詢結果中填入的。 仍然會執行額外的查詢來引入相關資料。

回傳 $this

查詢物件本身

                public function innerJoinWith($with, $eagerLoading = true)
{
    return $this->joinWith($with, $eagerLoading, 'INNER JOIN');
}

            
inverseOf() public method

定義於: yii\db\ActiveRelationTrait::inverseOf()

設定作為此關聯反向關聯的關聯名稱。

例如,一個客戶有多個訂單,這表示 "orders" 關聯的反向是 "customer"。 如果設定此屬性,則將透過指定的關聯引用主要記錄。 例如,$customer->orders[0]->customer$customer 將是相同的物件,並且存取訂單的客戶端將不會觸發新的 DB 查詢。

yii\db\ActiveRecord 類別中宣告關聯時,請使用此方法,例如在 Customer 模型中

public function getOrders()
{
    return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
}

這也可用於 Order 模型,但請謹慎使用

public function getCustomer()
{
    return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
}

在這種情況下,結果將取決於訂單的載入方式。 假設客戶有多個訂單。 如果僅載入一個訂單

$orders = Order::find()->where(['id' => 1])->all();
$customerOrders = $orders[0]->customer->orders;

變數 $customerOrders 將僅包含一個訂單。 如果訂單像這樣載入

$orders = Order::find()->with('customer')->where(['customer_id' => 1])->all();
$customerOrders = $orders[0]->customer->orders;

變數 $customerOrders 將包含客戶的所有訂單。

public $this inverseOf ( $relationName )
$relationName string

作為此關聯反向關聯的關聯名稱。

回傳 $this

關聯物件本身。

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

            
isEmpty() protected method

定義於: yii\db\QueryTrait::isEmpty()

回傳一個值,指示給定值是否為「空」。

如果滿足以下條件之一,則該值被視為「空」

  • 它是 null
  • 空字串 (''),
  • 僅包含空白字元的字串,
  • 或空陣列。
protected boolean isEmpty ( $value )
$value mixed
回傳 布林值

如果值為空

                protected function isEmpty($value)
{
    return $value === '' || $value === [] || $value === null || is_string($value) && trim($value) === '';
}

            
join() public method

定義於: yii\db\Query::join()

將 JOIN 部分附加到查詢。

第一個參數指定了 join 的類型。

public $this join ( $type, $table, $on '', $params = [] )
$type string

Join 的類型,例如 INNER JOIN、LEFT JOIN。

$table string|array

要聯結的資料表或子查詢。

使用字串來表示要聯結的資料表名稱。 資料表名稱可以包含結構描述前綴 (例如 'public.user') 和/或資料表別名 (例如 'user u')。 除非資料表名稱包含括號(表示資料表以子查詢或 DB 運算式給出),否則此方法將自動引用資料表名稱。

您也可以將資料表指定為具有一個元素的陣列,並使用陣列鍵作為資料表別名(例如 ['u' => 'user'])。

若要聯結子查詢,請使用具有一個元素的陣列,值設定為表示子查詢的 yii\db\Query 物件,且對應的鍵表示別名。

$on string|array

應該出現在 ON 部分的 join 條件。請參考 where() 以了解如何指定此參數。

請注意,where() 的陣列格式設計為將欄位與值而不是欄位與欄位匹配,因此以下程式碼不會如預期般運作: ['post.author_id' => 'user.id'],它會將 post.author_id 欄位值與字串 'user.id' 進行匹配。建議在此處使用字串語法,它更適合用於 join

'post.author_id = user.id'
$params array

要綁定到查詢的參數 (name => value)。

回傳 $this

查詢物件本身

                public function join($type, $table, $on = '', $params = [])
{
    $this->join[] = [$type, $table, $on];
    return $this->addParams($params);
}

            
joinWith() public method

與指定的關聯聯結。

此方法允許您重複使用現有的關聯定義來執行 JOIN 查詢。根據指定關聯的定義,此方法將在當前查詢中附加一個或多個 JOIN 語句。

如果 $eagerLoading 參數為 true,此方法也將對指定的關聯執行預先載入,這相當於使用指定的關聯呼叫 with()

請注意,由於將執行 JOIN 查詢,您有責任消除欄位名稱的歧義。

此方法與 with() 的不同之處在於,它將為主要表格建立並執行 JOIN SQL 語句。當 $eagerLoading 為 true 時,它將額外使用指定的關聯呼叫 with()

public $this joinWith ( $with, $eagerLoading true, $joinType 'LEFT JOIN' )
$with string|array

要 join 的關聯。這可以是字串(表示關聯名稱)或具有以下語意的陣列

  • 每個陣列元素代表單個關聯。
  • 您可以將關聯名稱指定為陣列鍵,並提供匿名函式作為陣列值,該函式可用於即時修改關聯查詢。
  • 如果關聯查詢不需要修改,您可以將關聯名稱用作陣列值。

關聯名稱可以選擇性地包含關聯表格的別名(例如 books b)。

也可以指定子關聯,語法請參閱 with()

以下是一些範例

// find all orders that contain books, and eager loading "books"
Order::find()->joinWith('books', true, 'INNER JOIN')->all();
// find all orders, eager loading "books", and sort the orders and books by the book names.
Order::find()->joinWith([
    'books' => function (\yii\db\ActiveQuery $query) {
        $query->orderBy('item.name');
    }
])->all();
// find all orders that contain books of the category 'Science fiction', using the alias "b" for the books table
Order::find()->joinWith(['books b'], true, 'INNER JOIN')->where(['b.category' => 'Science fiction'])->all();

別名語法自 2.0.7 版本起可用。

$eagerLoading boolean|array

是否預先載入 $with 中指定的關聯。當這是布林值時,它適用於 $with 中指定的所有關聯。使用陣列明確列出 $with 中哪些關聯需要預先載入。請注意,這並不表示關聯是從查詢結果中填入的。仍然會執行額外的查詢以帶入相關資料。預設值為 true

$joinType string|array

$with 中指定的關聯的 join 類型。當這是字串時,它適用於 $with 中指定的所有關聯。使用 relationName => joinType 格式的陣列,為不同的關聯指定不同的 join 類型。

回傳 $this

查詢物件本身

                public function joinWith($with, $eagerLoading = true, $joinType = 'LEFT JOIN')
{
    $relations = [];
    foreach ((array) $with as $name => $callback) {
        if (is_int($name)) {
            $name = $callback;
            $callback = null;
        }
        if (preg_match('/^(.*?)(?:\s+AS\s+|\s+)(\w+)$/i', $name, $matches)) {
            // relation is defined with an alias, adjust callback to apply alias
            list(, $relation, $alias) = $matches;
            $name = $relation;
            $callback = function ($query) use ($callback, $alias) {
                /* @var $query ActiveQuery */
                $query->alias($alias);
                if ($callback !== null) {
                    call_user_func($callback, $query);
                }
            };
        }
        if ($callback === null) {
            $relations[] = $name;
        } else {
            $relations[$name] = $callback;
        }
    }
    $this->joinWith[] = [$relations, $eagerLoading, $joinType];
    return $this;
}

            
leftJoin() public method

定義於: yii\db\Query::leftJoin()

將 LEFT OUTER JOIN 部分附加到查詢。

public $this leftJoin ( $table, $on '', $params = [] )
$table string|array

要聯結的資料表或子查詢。

使用字串來表示要聯結的資料表名稱。 資料表名稱可以包含結構描述前綴 (例如 'public.user') 和/或資料表別名 (例如 'user u')。 除非資料表名稱包含括號(表示資料表以子查詢或 DB 運算式給出),否則此方法將自動引用資料表名稱。

您也可以將資料表指定為具有一個元素的陣列,並使用陣列鍵作為資料表別名(例如 ['u' => 'user'])。

若要聯結子查詢,請使用具有一個元素的陣列,值設定為表示子查詢的 yii\db\Query 物件,且對應的鍵表示別名。

$on string|array

應出現在 ON 部分的聯結條件。 有關如何指定此參數,請參閱 join()

$params array

要繫結到查詢的參數(名稱 => 值)

回傳 $this

查詢物件本身

                public function leftJoin($table, $on = '', $params = [])
{
    $this->join[] = ['LEFT JOIN', $table, $on];
    return $this->addParams($params);
}

            
limit() public method

定義於: yii\db\QueryTrait::limit()

設定查詢的 LIMIT 部分。

public $this limit ( $limit )
$limit integer|yii\db\ExpressionInterface|null

限制。使用 null 或負值停用限制。

回傳 $this

查詢物件本身

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

            
max() public method

定義於: yii\db\Query::max()

回傳指定欄位值的最大值。

public mixed max ( $q, $db null )
$q string

欄位名稱或運算式。請確保您已正確地 引用 運算式中的欄位名稱。

$db yii\db\Connection|null

用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 db 應用程式元件。

回傳 mixed

指定欄位值的最大值。

                public function max($q, $db = null)
{
    return $this->queryScalar("MAX($q)", $db);
}

            
min() public method

定義於: yii\db\Query::min()

回傳指定欄位值的最小值。

public mixed min ( $q, $db null )
$q string

欄位名稱或運算式。請確保您已正確地 引用 運算式中的欄位名稱。

$db yii\db\Connection|null

用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 db 應用程式元件。

回傳 mixed

指定欄位值的最小值。

                public function min($q, $db = null)
{
    return $this->queryScalar("MIN($q)", $db);
}

            
noCache() public method (自 2.0.14 版本起可用)

定義於: yii\db\Query::noCache()

為此 Query 停用查詢快取。

public $this noCache ( )
回傳 $this

Query 物件本身

                public function noCache()
{
    $this->queryCacheDuration = -1;
    return $this;
}

            
normalizeOrderBy() protected method

定義於: yii\db\QueryTrait::normalizeOrderBy()

正規化 ORDER BY 資料的格式。

protected array normalizeOrderBy ( $columns )
$columns array|string|yii\db\ExpressionInterface|null

要標準化的欄位值。請參閱 orderBy()addOrderBy()

                protected function normalizeOrderBy($columns)
{
    if (empty($columns)) {
        return [];
    } elseif ($columns instanceof ExpressionInterface) {
        return [$columns];
    } elseif (is_array($columns)) {
        return $columns;
    }
    $columns = preg_split('/\s*,\s*/', trim($columns), -1, PREG_SPLIT_NO_EMPTY);
    $result = [];
    foreach ($columns as $column) {
        if (preg_match('/^(.*?)\s+(asc|desc)$/i', $column, $matches)) {
            $result[$matches[1]] = strcasecmp($matches[2], 'desc') ? SORT_ASC : SORT_DESC;
        } else {
            $result[$column] = SORT_ASC;
        }
    }
    return $result;
}

            
normalizeSelect() protected method (自 2.0.21 版本起可用)

定義於: yii\db\Query::normalizeSelect()

正規化傳遞給 select()addSelect() 的 SELECT 欄位。

protected array normalizeSelect ( $columns )
$columns string|array|yii\db\ExpressionInterface

                protected function normalizeSelect($columns)
{
    if ($columns instanceof ExpressionInterface) {
        $columns = [$columns];
    } elseif (!is_array($columns)) {
        $columns = preg_split('/\s*,\s*/', trim((string)$columns), -1, PREG_SPLIT_NO_EMPTY);
    }
    $select = [];
    foreach ($columns as $columnAlias => $columnDefinition) {
        if (is_string($columnAlias)) {
            // Already in the normalized format, good for them
            $select[$columnAlias] = $columnDefinition;
            continue;
        }
        if (is_string($columnDefinition)) {
            if (
                preg_match('/^(.*?)(?i:\s+as\s+|\s+)([\w\-_\.]+)$/', $columnDefinition, $matches) &&
                !preg_match('/^\d+$/', $matches[2]) &&
                strpos($matches[2], '.') === false
            ) {
                // Using "columnName as alias" or "columnName alias" syntax
                $select[$matches[2]] = $matches[1];
                continue;
            }
            if (strpos($columnDefinition, '(') === false) {
                // Normal column name, just alias it to itself to ensure it's not selected twice
                $select[$columnDefinition] = $columnDefinition;
                continue;
            }
        }
        // Either a string calling a function, DB expression, or sub-query
        $select[] = $columnDefinition;
    }
    return $select;
}

            
off() public method

定義於: yii\base\Component::off()

從此元件卸離現有的事件處理常式。

此方法與 on() 方法相反。

注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理常式,而使用與此萬用字元匹配的純名稱註冊的處理常式將保持不變。

另請參閱 on()

public boolean off ( $name, $handler null )
$name string

事件名稱

$handler callable|null

要移除的事件處理常式。如果為 null,則會移除附加到具名事件的所有處理常式。

回傳 布林值

如果找到並分離了處理常式

                public function off($name, $handler = null)
{
    $this->ensureBehaviors();
    if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
        return false;
    }
    if ($handler === null) {
        unset($this->_events[$name], $this->_eventWildcards[$name]);
        return true;
    }
    $removed = false;
    // plain event names
    if (isset($this->_events[$name])) {
        foreach ($this->_events[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_events[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_events[$name] = array_values($this->_events[$name]);
            return true;
        }
    }
    // wildcard event names
    if (isset($this->_eventWildcards[$name])) {
        foreach ($this->_eventWildcards[$name] as $i => $event) {
            if ($event[0] === $handler) {
                unset($this->_eventWildcards[$name][$i]);
                $removed = true;
            }
        }
        if ($removed) {
            $this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
            // remove empty wildcards to save future redundant regex checks:
            if (empty($this->_eventWildcards[$name])) {
                unset($this->_eventWildcards[$name]);
            }
        }
    }
    return $removed;
}

            
offset() public method

定義於: yii\db\QueryTrait::offset()

設定查詢的 OFFSET 部分。

public $this offset ( $offset )
$offset integer|yii\db\ExpressionInterface|null

偏移量。使用 null 或負值停用偏移量。

回傳 $this

查詢物件本身

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

            
on() public method

定義於: yii\base\Component::on()

將事件處理常式附加到事件。

事件處理常式必須是有效的 PHP 回呼。以下是一些範例

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

事件處理常式必須使用以下簽名定義,

function ($event)

其中 $event 是一個 yii\base\Event 物件,其中包含與事件相關聯的參數。

自 2.0.14 版本起,您可以將事件名稱指定為萬用字元模式

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});

另請參閱 off()

public void on ( $name, $handler, $data null, $append true )
$name string

事件名稱

$handler callable

事件處理常式

$data mixed

事件觸發時要傳遞給事件處理常式的資料。當事件處理常式被調用時,可以透過 yii\base\Event::$data 存取此資料。

$append 布林值

是否將新的事件處理常式附加到現有處理常式列表的末尾。如果為 false,則新的處理常式將插入到現有處理常式列表的開頭。

                public function on($name, $handler, $data = null, $append = true)
{
    $this->ensureBehaviors();
    if (strpos($name, '*') !== false) {
        if ($append || empty($this->_eventWildcards[$name])) {
            $this->_eventWildcards[$name][] = [$handler, $data];
        } else {
            array_unshift($this->_eventWildcards[$name], [$handler, $data]);
        }
        return;
    }
    if ($append || empty($this->_events[$name])) {
        $this->_events[$name][] = [$handler, $data];
    } else {
        array_unshift($this->_events[$name], [$handler, $data]);
    }
}

            
onCondition() public method

為關聯式查詢設定 ON 條件。

當呼叫 yii\db\ActiveQuery::joinWith() 時,條件將在 ON 部分中使用。否則,條件將在查詢的 WHERE 部分中使用。

yii\db\ActiveRecord 類別中宣告關聯時,使用此方法指定額外的條件

public function getActiveUsers()
{
    return $this->hasMany(User::class, ['id' => 'user_id'])
                ->onCondition(['active' => true]);
}

請注意,此條件適用於 join 的情況,以及在提取相關記錄時。因此,條件中只能使用相關表格的欄位。嘗試存取主要記錄的欄位將在非 join 查詢中導致錯誤。

public $this onCondition ( $condition, $params = [] )
$condition string|array

ON 條件。請參考 yii\db\Query::where() 以了解如何指定此參數。

$params array

要綁定到查詢的參數 (name => value)。

回傳 $this

查詢物件本身

                public function onCondition($condition, $params = [])
{
    $this->on = $condition;
    $this->addParams($params);
    return $this;
}

            
one() public method

執行查詢並回傳單列結果。

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

用於建立 DB 命令的 DB 連線。如果為 null,將使用 $modelClass 傳回的 DB 連線。

回傳 yii\db\ActiveRecord|array|null

查詢結果的單一列。根據 asArray() 的設定,查詢結果可能是陣列或 ActiveRecord 物件。如果查詢沒有結果,將傳回 null

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

            
orFilterHaving() public method (自 2.0.11 版本起可用)

定義於: yii\db\Query::orFilterHaving()

將額外的 HAVING 條件新增到現有的條件,但忽略空運算元

新的條件和現有的條件將使用 OR 運算子進行 join。

此方法與 orHaving() 類似。主要區別在於此方法將移除空的查詢運算元。因此,此方法最適合基於使用者輸入的篩選值來建立查詢條件。

參見

public array orFilterHaving ( array $condition )
$condition array

新的 HAVING 條件。請參考 having() 以了解如何指定此參數。

回傳 $this

查詢物件本身

                public function orFilterHaving(array $condition)
{
    $condition = $this->filterCondition($condition);
    if ($condition !== []) {
        $this->orHaving($condition);
    }
    return $this;
}

            
orFilterWhere() public method

定義於: yii\db\QueryTrait::orFilterWhere()

將額外的 WHERE 條件新增到現有的條件,但忽略空運算元

新的條件和現有的條件將使用 'OR' 運算子進行 join。

此方法與 orWhere() 類似。主要區別在於此方法將移除空的查詢運算元。因此,此方法最適合基於使用者輸入的篩選值來建立查詢條件。

參見

public $this orFilterWhere ( array $condition )
$condition array

新的 WHERE 條件。請參考 where() 以了解如何指定此參數。

回傳 $this

查詢物件本身

                public function orFilterWhere(array $condition)
{
    $condition = $this->filterCondition($condition);
    if ($condition !== []) {
        $this->orWhere($condition);
    }
    return $this;
}

            
orHaving() public method

定義於: yii\db\Query::orHaving()

將額外的 HAVING 條件新增到現有的條件。

新的條件和現有的條件將使用 OR 運算子進行 join。

參見

public $this orHaving ( $condition, $params = [] )
$condition string|array|yii\db\ExpressionInterface

新的 HAVING 條件。請參考 where() 以了解如何指定此參數。

$params array

要綁定到查詢的參數 (name => value)。

回傳 $this

查詢物件本身

                public function orHaving($condition, $params = [])
{
    if ($this->having === null) {
        $this->having = $condition;
    } else {
        $this->having = ['or', $this->having, $condition];
    }
    $this->addParams($params);
    return $this;
}

            
orOnCondition() public method

將額外的 ON 條件新增到現有的條件。

新的條件和現有的條件將使用 'OR' 運算子進行 join。

參見

public $this orOnCondition ( $condition, $params = [] )
$condition string|array

新的 ON 條件。請參考 where() 以了解如何指定此參數。

$params array

要綁定到查詢的參數 (name => value)。

回傳 $this

查詢物件本身

                public function orOnCondition($condition, $params = [])
{
    if ($this->on === null) {
        $this->on = $condition;
    } else {
        $this->on = ['or', $this->on, $condition];
    }
    $this->addParams($params);
    return $this;
}

            
orWhere() public method

定義於: yii\db\QueryTrait::orWhere()

將額外的 WHERE 條件新增到現有的條件。

新的條件和現有的條件將使用 'OR' 運算子進行 join。

參見

public $this orWhere ( $condition )
$condition string|array|yii\db\ExpressionInterface

新的 WHERE 條件。請參考 where() 以了解如何指定此參數。

回傳 $this

查詢物件本身

                public function orWhere($condition)
{
    if ($this->where === null) {
        $this->where = $condition;
    } else {
        $this->where = ['or', $this->where, $condition];
    }
    return $this;
}

            
orderBy() public method

定義於: yii\db\QueryTrait::orderBy()

設定查詢的 ORDER BY 部分。

另請參閱 addOrderBy()

public $this orderBy ( $columns )
$columns string|array|yii\db\ExpressionInterface|null

要排序的欄位(和方向)。欄位可以使用字串(例如 "id ASC, name DESC")或陣列(例如 ['id' => SORT_ASC, 'name' => SORT_DESC])指定。

除非欄位包含一些括號 (表示欄位包含 DB 運算式),否則此方法將自動引用欄位名稱。

請注意,如果您的 order-by 是包含逗號的運算式,您應始終使用陣列來表示 order-by 資訊。否則,此方法將無法正確判斷 order-by 欄位。

自 2.0.7 版起,可以傳遞 yii\db\ExpressionInterface 物件,以純 SQL 顯式指定 ORDER BY 部分。

回傳 $this

查詢物件本身

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

            
params() public method

定義於: yii\db\Query::params()

設定要繫結到查詢的參數。

另請參閱 addParams()

public $this params ( $params )
$params array

依參數預留位置索引的查詢參數值列表。例如,[':name' => 'Dan', ':age' => 31]

回傳 $this

查詢物件本身

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

            
populate() public method

將原始查詢結果轉換為此查詢指定的格式。

此方法在內部用於將從資料庫擷取的資料轉換為此查詢所需的格式。

public array populate ( $rows )
$rows array

來自資料庫的原始查詢結果

回傳 array

轉換後的查詢結果

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

            
populateRelation() public method

定義於: yii\db\ActiveRelationTrait::populateRelation()

尋找相關記錄並將其填入主要模型。

public array populateRelation ( $name, &$primaryModels )
$name string

關聯名稱

$primaryModels array

主要模型

回傳 array

相關模型

拋出 yii\base\InvalidConfigException

如果 $link 無效

                public function populateRelation($name, &$primaryModels)
{
    if (!is_array($this->link)) {
        throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
    }
    if ($this->via instanceof self) {
        // via junction table
        /* @var $viaQuery ActiveRelationTrait */
        $viaQuery = $this->via;
        $viaModels = $viaQuery->findJunctionRows($primaryModels);
        $this->filterByModels($viaModels);
    } elseif (is_array($this->via)) {
        // via relation
        /* @var $viaQuery ActiveRelationTrait|ActiveQueryTrait */
        list($viaName, $viaQuery) = $this->via;
        if ($viaQuery->asArray === null) {
            // inherit asArray from primary query
            $viaQuery->asArray($this->asArray);
        }
        $viaQuery->primaryModel = null;
        $viaModels = array_filter($viaQuery->populateRelation($viaName, $primaryModels));
        $this->filterByModels($viaModels);
    } else {
        $this->filterByModels($primaryModels);
    }
    if (!$this->multiple && count($primaryModels) === 1) {
        $model = $this->one();
        $primaryModel = reset($primaryModels);
        if ($primaryModel instanceof ActiveRecordInterface) {
            $primaryModel->populateRelation($name, $model);
        } else {
            $primaryModels[key($primaryModels)][$name] = $model;
        }
        if ($this->inverseOf !== null) {
            $this->populateInverseRelation($primaryModels, [$model], $name, $this->inverseOf);
        }
        return [$model];
    }
    // https://github.com/yiisoft/yii2/issues/3197
    // delay indexing related models after buckets are built
    $indexBy = $this->indexBy;
    $this->indexBy = null;
    $models = $this->all();
    if (isset($viaModels, $viaQuery)) {
        $buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery);
    } else {
        $buckets = $this->buildBuckets($models, $this->link);
    }
    $this->indexBy = $indexBy;
    if ($this->indexBy !== null && $this->multiple) {
        $buckets = $this->indexBuckets($buckets, $this->indexBy);
    }
    $link = array_values($this->link);
    if (isset($viaQuery)) {
        $deepViaQuery = $viaQuery;
        while ($deepViaQuery->via) {
            $deepViaQuery = is_array($deepViaQuery->via) ? $deepViaQuery->via[1] : $deepViaQuery->via;
        };
        $link = array_values($deepViaQuery->link);
    }
    foreach ($primaryModels as $i => $primaryModel) {
        $keys = null;
        if ($this->multiple && count($link) === 1) {
            $primaryModelKey = reset($link);
            $keys = isset($primaryModel[$primaryModelKey]) ? $primaryModel[$primaryModelKey] : null;
        }
        if (is_array($keys)) {
            $value = [];
            foreach ($keys as $key) {
                $key = $this->normalizeModelKey($key);
                if (isset($buckets[$key])) {
                    if ($this->indexBy !== null) {
                        // if indexBy is set, array_merge will cause renumbering of numeric array
                        foreach ($buckets[$key] as $bucketKey => $bucketValue) {
                            $value[$bucketKey] = $bucketValue;
                        }
                    } else {
                        $value = array_merge($value, $buckets[$key]);
                    }
                }
            }
        } else {
            $key = $this->getModelKey($primaryModel, $link);
            $value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null);
        }
        if ($primaryModel instanceof ActiveRecordInterface) {
            $primaryModel->populateRelation($name, $value);
        } else {
            $primaryModels[$i][$name] = $value;
        }
    }
    if ($this->inverseOf !== null) {
        $this->populateInverseRelation($primaryModels, $models, $name, $this->inverseOf);
    }
    return $models;
}

            
prepare() public method

準備建構 SQL。

yii\db\QueryBuilder 開始從查詢物件建構 SQL 時,會呼叫此方法。您可以覆寫此方法,以在將查詢轉換為 SQL 語句時執行一些最終準備工作。

public $this prepare ( $builder )
$builder yii\db\QueryBuilder
回傳 $this

預備好的查詢實例,yii\db\QueryBuilder 將使用它來建構 SQL

                public function prepare($builder)
{
    // NOTE: because the same ActiveQuery may be used to build different SQL statements
    // (e.g. by ActiveDataProvider, one for count query, the other for row data query,
    // it is important to make sure the same ActiveQuery can be used to build SQL statements
    // multiple times.
    if (!empty($this->joinWith)) {
        $this->buildJoinWith();
        $this->joinWith = null;    // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687
    }
    if (empty($this->from)) {
        $this->from = [$this->getPrimaryTableName()];
    }
    if (empty($this->select) && !empty($this->join)) {
        list(, $alias) = $this->getTableNameAndAlias();
        $this->select = ["$alias.*"];
    }
    if ($this->primaryModel === null) {
        // eager loading
        $query = Query::create($this);
    } else {
        // lazy loading of a relation
        $where = $this->where;
        if ($this->via instanceof self) {
            // via junction table
            $viaModels = $this->via->findJunctionRows([$this->primaryModel]);
            $this->filterByModels($viaModels);
        } elseif (is_array($this->via)) {
            // via relation
            /* @var $viaQuery ActiveQuery */
            list($viaName, $viaQuery, $viaCallableUsed) = $this->via;
            if ($viaQuery->multiple) {
                if ($viaCallableUsed) {
                    $viaModels = $viaQuery->all();
                } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
                    $viaModels = $this->primaryModel->$viaName;
                } else {
                    $viaModels = $viaQuery->all();
                    $this->primaryModel->populateRelation($viaName, $viaModels);
                }
            } else {
                if ($viaCallableUsed) {
                    $model = $viaQuery->one();
                } elseif ($this->primaryModel->isRelationPopulated($viaName)) {
                    $model = $this->primaryModel->$viaName;
                } else {
                    $model = $viaQuery->one();
                    $this->primaryModel->populateRelation($viaName, $model);
                }
                $viaModels = $model === null ? [] : [$model];
            }
            $this->filterByModels($viaModels);
        } else {
            $this->filterByModels([$this->primaryModel]);
        }
        $query = Query::create($this);
        $this->where = $where;
    }
    if (!empty($this->on)) {
        $query->andWhere($this->on);
    }
    return $query;
}

            
queryScalar() protected method

透過先設定 select() 來查詢純量值。

還原 select 的值,使此查詢可重複使用。

protected boolean|string|null queryScalar ( $selectExpression, $db )
$selectExpression string|yii\db\ExpressionInterface
$db yii\db\Connection|null

用於執行查詢的資料庫連線。

拋出 Throwable

如果無法建立命令

                protected function queryScalar($selectExpression, $db)
{
    /* @var $modelClass ActiveRecord */
    $modelClass = $this->modelClass;
    if ($db === null) {
        $db = $modelClass::getDb();
    }
    if ($this->sql === null) {
        return parent::queryScalar($selectExpression, $db);
    }
    $command = (new Query())->select([$selectExpression])
        ->from(['c' => "({$this->sql})"])
        ->params($this->params)
        ->createCommand($db);
    $this->setCommandCache($command);
    return $command->queryScalar();
}

            
rightJoin() public method

定義於: yii\db\Query::rightJoin()

將 RIGHT OUTER JOIN 部分附加到查詢。

public $this rightJoin ( $table, $on '', $params = [] )
$table string|array

要聯結的資料表或子查詢。

使用字串來表示要聯結的資料表名稱。 資料表名稱可以包含結構描述前綴 (例如 'public.user') 和/或資料表別名 (例如 'user u')。 除非資料表名稱包含括號(表示資料表以子查詢或 DB 運算式給出),否則此方法將自動引用資料表名稱。

您也可以將資料表指定為具有一個元素的陣列,並使用陣列鍵作為資料表別名(例如 ['u' => 'user'])。

若要聯結子查詢,請使用具有一個元素的陣列,值設定為表示子查詢的 yii\db\Query 物件,且對應的鍵表示別名。

$on string|array

應出現在 ON 部分的聯結條件。 有關如何指定此參數,請參閱 join()

$params array

要繫結到查詢的參數(名稱 => 值)

回傳 $this

查詢物件本身

                public function rightJoin($table, $on = '', $params = [])
{
    $this->join[] = ['RIGHT JOIN', $table, $on];
    return $this->addParams($params);
}

            
scalar() public method

定義於: yii\db\Query::scalar()

以純量值形式回傳查詢結果。

傳回的值將是查詢結果的第一列中的第一個欄位。

public string|integer|null|false scalar ( $db null )
$db yii\db\Connection|null

用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 db 應用程式元件。

回傳 string|integer|null|false

查詢結果的第一列中第一個欄位的值。如果查詢結果為空,則傳回 False。

                public function scalar($db = null)
{
    if ($this->emulateExecution) {
        return null;
    }
    return $this->createCommand($db)->queryScalar();
}

            
select() public method

Defined in: yii\db\Query::select()

設定查詢的 SELECT 部分。

public $this select ( $columns, $option null )
$columns string|array|yii\db\ExpressionInterface

要選擇的欄位。欄位可以使用字串 (例如 "id, name") 或陣列 (例如 ['id', 'name']) 指定。欄位可以加上表格名稱前綴 (例如 "user.id") 和/或 包含欄位別名 (例如 "user.id AS user_id")。除非欄位包含括號 (表示欄位包含資料庫運算式),否則此方法將自動引用欄位名稱。資料庫運算式也可以 yii\db\ExpressionInterface 物件的形式傳入。

請注意,如果您要選擇像 CONCAT(first_name, ' ', last_name) 這樣的運算式,則應使用陣列來指定欄位。否則,運算式可能會被錯誤地拆分為多個部分。

當欄位以陣列形式指定時,您也可以使用陣列鍵作為欄位別名 (如果欄位不需要別名,請不要使用字串鍵)。

從 2.0.1 版本開始,您還可以選擇子查詢作為欄位,方法是將每個這樣的欄位指定為代表子查詢的 Query 實例。

$option string|null

應附加到 'SELECT' 關鍵字的額外選項。例如,在 MySQL 中,可以使用 'SQL_CALC_FOUND_ROWS' 選項。

回傳 $this

查詢物件本身

                public function select($columns, $option = null)
{
    $this->select = $this->normalizeSelect($columns);
    $this->selectOption = $option;
    return $this;
}

            
setCommandCache() protected method (available since version 2.0.14)

Defined in: yii\db\Query::setCommandCache()

如果此查詢已啟用快取,則設定 $command 快取。

protected yii\db\Command setCommandCache ( $command )
$command yii\db\Command

                protected function setCommandCache($command)
{
    if ($this->queryCacheDuration !== null || $this->queryCacheDependency !== null) {
        $duration = $this->queryCacheDuration === true ? null : $this->queryCacheDuration;
        $command->cache($duration, $this->queryCacheDependency);
    }
    return $command;
}

            
sum() public method

Defined in: yii\db\Query::sum()

回傳指定欄位值的總和。

public mixed sum ( $q, $db null )
$q string

欄位名稱或運算式。請確保您已正確地 引用 運算式中的欄位名稱。

$db yii\db\Connection|null

用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 db 應用程式元件。

回傳 mixed

指定欄位值的總和。

                public function sum($q, $db = null)
{
    if ($this->emulateExecution) {
        return 0;
    }
    return $this->queryScalar("SUM($q)", $db);
}

            
trigger() public method

Defined in: yii\base\Component::trigger()

觸發事件。

此方法表示事件的發生。它會調用事件的所有附加處理程序,包括類別層級的處理程序。

public void trigger ( $name, yii\base\Event $event null )
$name string

事件名稱

$event yii\base\Event|null

事件實例。如果未設定,將會建立預設的 yii\base\Event 物件。

                public function trigger($name, Event $event = null)
{
    $this->ensureBehaviors();
    $eventHandlers = [];
    foreach ($this->_eventWildcards as $wildcard => $handlers) {
        if (StringHelper::matchWildcard($wildcard, $name)) {
            $eventHandlers[] = $handlers;
        }
    }
    if (!empty($this->_events[$name])) {
        $eventHandlers[] = $this->_events[$name];
    }
    if (!empty($eventHandlers)) {
        $eventHandlers = call_user_func_array('array_merge', $eventHandlers);
        if ($event === null) {
            $event = new Event();
        }
        if ($event->sender === null) {
            $event->sender = $this;
        }
        $event->handled = false;
        $event->name = $name;
        foreach ($eventHandlers as $handler) {
            $event->data = $handler[1];
            call_user_func($handler[0], $event);
            // stop further handling if the event is handled
            if ($event->handled) {
                return;
            }
        }
    }
    // invoke class-level attached handlers
    Event::trigger($this, $name, $event);
}

            
union() public method

Defined in: yii\db\Query::union()

使用 UNION 運算子附加 SQL 陳述式。

public $this union ( $sql, $all false )
$sql string|yii\db\Query

要使用 UNION 附加的 SQL 陳述式

$all 布林值

如果使用 UNION ALL 則為 TRUE,如果使用 UNION 則為 FALSE

回傳 $this

查詢物件本身

                public function union($sql, $all = false)
{
    $this->union[] = ['query' => $sql, 'all' => $all];
    return $this;
}

            
via() public method

Defined in: yii\db\ActiveRelationTrait::via()

指定與連接資料表相關聯的關聯。

yii\db\ActiveRecord 類別中宣告關聯時,使用此方法指定樞紐記錄/表格

class Order extends ActiveRecord
{
   public function getOrderItems() {
       return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
   }

   public function getItems() {
       return $this->hasMany(Item::class, ['id' => 'item_id'])
                   ->via('orderItems');
   }
}
public $this via ( $relationName, callable $callable null )
$relationName string

關聯名稱。這指的是在 $primaryModel 中宣告的關聯。

$callable callable|null

用於自訂與聯結表相關聯的關聯的 PHP 回呼函式。其簽章應為 function($query),其中 $query 是要自訂的查詢。

回傳 $this

關聯物件本身。

                public function via($relationName, callable $callable = null)
{
    $relation = $this->primaryModel->getRelation($relationName);
    $callableUsed = $callable !== null;
    $this->via = [$relationName, $relation, $callableUsed];
    if ($callable !== null) {
        call_user_func($callable, $relation);
    }
    return $this;
}

            
viaTable() public method

為關聯式查詢指定連接資料表。

yii\db\ActiveRecord 類別中宣告關聯時,使用此方法指定聯結表

public function getItems()
{
    return $this->hasMany(Item::class, ['id' => 'item_id'])
                ->viaTable('order_item', ['order_id' => 'id']);
}

另請參閱 via()

public $this viaTable ( $tableName, $link, callable $callable null )
$tableName string

聯結表的名稱。

$link array

聯結表與 $primaryModel 關聯的表格之間的連結。陣列的鍵代表聯結表中的欄位,值代表 $primaryModel 表格中的欄位。

$callable callable|null

用於自訂與聯結表相關聯的關聯的 PHP 回呼函式。其簽章應為 function($query),其中 $query 是要自訂的查詢。

回傳 $this

查詢物件本身

拋出 yii\base\InvalidConfigException

當查詢未正確初始化時

                public function viaTable($tableName, $link, callable $callable = null)
{
    $modelClass = $this->primaryModel ? get_class($this->primaryModel) : $this->modelClass;
    $relation = new self($modelClass, [
        'from' => [$tableName],
        'link' => $link,
        'multiple' => true,
        'asArray' => true,
    ]);
    $this->via = $relation;
    if ($callable !== null) {
        call_user_func($callable, $relation);
    }
    return $this;
}

            
where() public method

Defined in: yii\db\QueryTrait::where()

設定查詢的 WHERE 部分。

請參閱 yii\db\QueryInterface::where() 以取得詳細文件。

參見

public $this where ( $condition )
$condition string|array|yii\db\ExpressionInterface

應放在 WHERE 部分的條件。

回傳 $this

查詢物件本身

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

            
with() public method

Defined in: yii\db\ActiveQueryTrait::with()

指定應執行此查詢的關聯。

此方法的參數可以是一個或多個字串,或是一個關聯名稱和可選回呼函式的陣列,用於自訂關聯。

關聯名稱可以參考 $modelClass 中定義的關聯,或代表相關記錄關聯的子關聯。 例如,orders.address 表示在對應於 orders 關聯的模型類別中定義的 address 關聯。

以下是一些使用範例

// find customers together with their orders and country
Customer::find()->with('orders', 'country')->all();
// find customers together with their orders and the orders' shipping address
Customer::find()->with('orders.address')->all();
// find customers together with their country and orders of status 1
Customer::find()->with([
    'orders' => function (\yii\db\ActiveQuery $query) {
        $query->andWhere('status = 1');
    },
    'country',
])->all();

您可以多次調用 with()。每次調用都會將關聯添加到現有的關聯。例如,以下兩個陳述式是等效的

Customer::find()->with('orders', 'country')->all();
Customer::find()->with('orders')->with('country')->all();
public $this with ( )
回傳 $this

查詢物件本身

                public function with()
{
    $with = func_get_args();
    if (isset($with[0]) && is_array($with[0])) {
        // the parameter is given as an array
        $with = $with[0];
    }
    if (empty($this->with)) {
        $this->with = $with;
    } elseif (!empty($with)) {
        foreach ($with as $name => $value) {
            if (is_int($name)) {
                // repeating relation is fine as normalizeRelations() handle it well
                $this->with[] = $value;
            } else {
                $this->with[$name] = $value;
            }
        }
    }
    return $this;
}

            
withQuery() public method (available since version 2.0.35)

Defined in: yii\db\Query::withQuery()

使用 WITH 語法預先加入 SQL 陳述式。

public $this withQuery ( $query, $alias, $recursive false )
$query string|yii\db\Query

要使用 WITH 前置的 SQL 陳述式

$alias string

WITH 結構中的查詢別名

$recursive 布林值

如果使用 WITH RECURSIVE 則為 TRUE,如果使用 WITH 則為 FALSE

回傳 $this

查詢物件本身

                public function withQuery($query, $alias, $recursive = false)
{
    $this->withQueries[] = ['query' => $query, 'alias' => $alias, 'recursive' => $recursive];
    return $this;
}

            

事件詳情

隱藏繼承的屬性

EVENT_INIT event of type yii\db\Event

透過 init() 初始化查詢時觸發的事件。