類別 yii\db\ActiveQuery
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() 則新增一個條件,該條件將新增至關聯式查詢聯結條件。
公共屬性
公開方法
保護方法
方法 | 描述 | 定義於 |
---|---|---|
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 |
屬性詳細資訊
當此查詢用於關聯內容時,要使用的聯結條件。當呼叫 yii\db\ActiveQuery::joinWith() 時,條件將用於 ON 部分。否則,條件將用於查詢的 WHERE 部分。請參閱 yii\db\Query::where(),以了解如何指定此參數。
另請參閱 onCondition()。
要執行以檢索 AR 記錄的 SQL 陳述式。這由 yii\db\ActiveRecord::findBySql() 設定。
方法詳細資訊
定義於: 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()");
}
定義於: 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]];
}
}
建構子。
public void __construct ( $modelClass, $config = [] ) | ||
$modelClass | string |
與此查詢相關聯的模型類別 |
$config | array |
要套用於新建立的查詢物件的組態 |
public function __construct($modelClass, $config = [])
{
$this->modelClass = $modelClass;
parent::__construct($config);
}
定義於: 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);
}
定義於: yii\base\Component::__isset()
檢查是否已設定屬性,即已定義且非 null。
此方法將依以下順序檢查並採取相應措施
- setter 定義的屬性:回傳屬性是否已設定
- 行為的屬性:回傳屬性是否已設定
- 對於不存在的屬性回傳
false
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 isset($component->property)
時,將會隱含地呼叫它。
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;
}
定義於: 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);
}
定義於: yii\db\Query::__toString()
回傳 Query 的 SQL 表示法
public string __toString ( ) |
public function __toString()
{
return serialize($this);
}
定義於: yii\base\Component::__unset()
將元件屬性設定為 null。
此方法將依以下順序檢查並採取相應措施
- setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是 PHP 魔術方法,當執行 unset($component->property)
時,將會隱含地呼叫它。
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);
}
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;
}
public $this addOrderBy ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface |
要排序的欄位 (和方向)。欄位可以使用字串 (例如 "id ASC, name 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;
}
public $this addParams ( $params ) | ||
$params | array |
依參數預留位置索引的查詢參數值列表。例如, |
回傳 | $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;
}
定義於: 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;
}
為 $modelClass 中定義的資料表定義別名。
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;
}
執行查詢並以陣列形式回傳所有結果。
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);
}
定義於: yii\db\Query::andFilterCompare()
為特定欄位新增篩選條件,並允許使用者選擇篩選運算子。
它為給定的欄位新增額外的 WHERE 條件,並根據給定值的前幾個字元判斷比較運算子。條件的加入方式與 andFilterWhere() 相同,因此會忽略空值。新的條件和現有的條件將使用 AND
運算子聯結。
比較運算子會根據給定值中的前幾個字元智慧地判斷。特別是,如果以下運算子作為給定值中的前導字元出現,則會識別它們
<
:欄位必須小於給定值。>
:欄位必須大於給定值。<=
:欄位必須小於或等於給定值。>=
:欄位必須大於或等於給定值。<>
:欄位不得與給定值相同。=
:欄位必須等於給定值。- 如果未偵測到上述任何運算子,將使用
$defaultOperator
。
public $this andFilterCompare ( $name, $value, $defaultOperator = '=' ) | ||
$name | string |
欄位名稱。 |
$value | string |
欄位值,可選擇性地在其前面加上比較運算子。 |
$defaultOperator | string |
當 |
回傳 | $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]);
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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);
}
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);
}
}
Defined in: yii\db\Query::average()
回傳指定欄位值的平均值。
public mixed average ( $q, $db = null ) | ||
$q | string |
欄位名稱或運算式。請確保您已正確地 引用 運算式中的欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 |
回傳 | mixed |
指定欄位值的平均值。 |
---|
public function average($q, $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->queryScalar("AVG($q)", $db);
}
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,
]);
}
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 [];
}
Defined in: yii\db\Query::cache()
為此 Query 啟用查詢快取。
public $this cache ( $duration = true, $dependency = null ) | ||
$duration | integer|true |
查詢結果在快取中保持有效的秒數。使用 0 表示快取資料永遠不會過期。使用負數表示不應使用查詢快取。使用布林值 |
$dependency | yii\caching\Dependency|null |
與快取結果相關聯的快取相依性。 |
回傳 | $this |
Query 物件本身 |
---|
public function cache($duration = true, $dependency = null)
{
$this->queryCacheDuration = $duration;
$this->queryCacheDependency = $dependency;
return $this;
}
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;
}
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;
}
::class
instead.
Defined in: yii\base\BaseObject::className()
回傳此類別的完整命名空間名稱。
public static string className ( ) | ||
回傳 | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
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;
}
Defined in: yii\db\Query::column()
執行查詢並回傳結果的第一個欄位。
public array column ( $db = null ) | ||
$db | yii\db\Connection|null |
用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 |
回傳 | 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;
}
Defined in: yii\db\Query::count()
回傳記錄數。
public integer|string|null count ( $q = '*', $db = null ) | ||
$q | string |
COUNT 運算式。預設為 '*'。請確保您已正確地 引用 運算式中的欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 陳述式的資料庫連線。如果未給定此參數(或為 null),將使用 |
回傳 | integer|string|null |
記錄數。結果可能是字串,具體取決於底層資料庫引擎,並且支援高於 32 位元 PHP 整數可以處理的整數值。 |
---|
public function count($q = '*', $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->queryScalar("COUNT($q)", $db);
}
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,
]);
}
建立可用於執行此查詢的 DB 命令。
public yii\db\Command createCommand ( $db = null ) | ||
$db | yii\db\Connection|null |
用於建立 DB 命令的 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;
}
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;
}
}
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;
}
Defined in: yii\base\Component::detachBehaviors()
從元件卸離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
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;
}
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,
]);
}
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;
}
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);
}
}
}
回傳一個值,指示查詢結果是否包含任何資料列。
public boolean exists ( $db = null ) | ||
$db | yii\db\Connection|null |
用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 |
回傳 | 布林值 |
查詢結果是否包含任何資料列。 |
---|
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();
}
定義於: 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;
}
定義於: 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;
}
定義於: 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;
}
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();
}
定義於: 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);
}
}
定義於: yii\db\Query::from()
設定查詢的 FROM 部分。
public $this from ( $tables ) | ||
$tables | string|array|yii\db\ExpressionInterface |
要從中選取的資料表。 這可以是字串 (例如 當資料表指定為陣列時,您也可以使用陣列鍵作為資料表別名(如果資料表不需要別名,請勿使用字串鍵)。 使用 Query 物件來表示子查詢。 在這種情況下,對應的陣列鍵將用作子查詢的別名。 若要以純 SQL 指定 以下是一些範例
|
回傳 | $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;
}
定義於: 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;
}
定義於: yii\base\Component::getBehaviors()
回傳附加到此元件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
回傳 | yii\base\Behavior[] |
附加到此元件的行為列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
protected string getPrimaryTableName ( ) | ||
回傳 | string |
主要資料表名稱 |
---|
protected function getPrimaryTableName()
{
/* @var $modelClass ActiveRecord */
$modelClass = $this->modelClass;
return $modelClass::tableName();
}
回傳 $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() 中使用的資料表名稱,依別名索引。
public string[] getTablesUsedInFrom ( ) | ||
回傳 | string[] |
以別名編製索引的表名稱 |
---|---|---|
拋出 | yii\base\InvalidConfigException |
public function getTablesUsedInFrom()
{
if (empty($this->from)) {
return $this->cleanUpTableNames([$this->getPrimaryTableName()]);
}
return parent::getTablesUsedInFrom();
}
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);
}
定義於: 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;
}
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;
}
定義於: 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);
}
定義於: 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;
}
定義於: 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);
}
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;
}
定義於: yii\db\QueryTrait::indexBy()
設定 indexBy() 屬性。
public $this indexBy ( $column ) | ||
$column | string|callable |
應依其索引查詢結果的欄位名稱。 這也可以是一個可調用項(例如匿名函數),它根據給定的資料列資料傳回索引值。 可調用項的簽章應為
|
回傳 | $this |
查詢物件本身 |
---|
public function indexBy($column)
{
$this->indexBy = $column;
return $this;
}
初始化物件。
此方法在建構函式的末尾調用。 預設實作將觸發 EVENT_INIT 事件。 如果您覆寫此方法,請確保在結尾調用父實作,以確保觸發事件。
public void init ( ) |
public function init()
{
parent::init();
$this->trigger(self::EVENT_INIT);
}
定義於: 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);
}
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');
}
定義於: 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;
}
定義於: 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) === '';
}
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() 的陣列格式設計為將欄位與值而不是欄位與欄位匹配,因此以下程式碼不會如預期般運作:
|
$params | array |
要綁定到查詢的參數 (name => value)。 |
回傳 | $this |
查詢物件本身 |
---|
public function join($type, $table, $on = '', $params = [])
{
$this->join[] = [$type, $table, $on];
return $this->addParams($params);
}
與指定的關聯聯結。
此方法允許您重複使用現有的關聯定義來執行 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 的關聯。這可以是字串(表示關聯名稱)或具有以下語意的陣列
關聯名稱可以選擇性地包含關聯表格的別名(例如 也可以指定子關聯,語法請參閱 with()。 以下是一些範例
別名語法自 2.0.7 版本起可用。 |
$eagerLoading | boolean|array |
是否預先載入 |
$joinType | string|array |
|
回傳 | $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;
}
將 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);
}
定義於: 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;
}
定義於: yii\db\Query::max()
回傳指定欄位值的最大值。
public mixed max ( $q, $db = null ) | ||
$q | string |
欄位名稱或運算式。請確保您已正確地 引用 運算式中的欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 |
回傳 | mixed |
指定欄位值的最大值。 |
---|
public function max($q, $db = null)
{
return $this->queryScalar("MAX($q)", $db);
}
定義於: yii\db\Query::min()
回傳指定欄位值的最小值。
public mixed min ( $q, $db = null ) | ||
$q | string |
欄位名稱或運算式。請確保您已正確地 引用 運算式中的欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 |
回傳 | mixed |
指定欄位值的最小值。 |
---|
public function min($q, $db = null)
{
return $this->queryScalar("MIN($q)", $db);
}
為此 Query 停用查詢快取。
public $this noCache ( ) | ||
回傳 | $this |
Query 物件本身 |
---|
public function noCache()
{
$this->queryCacheDuration = -1;
return $this;
}
定義於: 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;
}
定義於: 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;
}
定義於: 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;
}
定義於: 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;
}
將事件處理常式附加到事件。
事件處理常式必須是有效的 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]);
}
}
為關聯式查詢設定 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;
}
執行查詢並回傳單列結果。
public yii\db\ActiveRecord|array|null one ( $db = null ) | ||
$db | yii\db\Connection|null |
用於建立 DB 命令的 DB 連線。如果為 |
回傳 | yii\db\ActiveRecord|array|null |
查詢結果的單一列。根據 asArray() 的設定,查詢結果可能是陣列或 ActiveRecord 物件。如果查詢沒有結果,將傳回 |
---|
public function one($db = null)
{
$row = parent::one($db);
if ($row !== false) {
$models = $this->populate([$row]);
return reset($models) ?: null;
}
return null;
}
定義於: 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;
}
定義於: 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;
}
將額外的 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;
}
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;
}
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;
}
public $this orderBy ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface|null |
要排序的欄位(和方向)。欄位可以使用字串(例如 除非欄位包含一些括號 (表示欄位包含 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;
}
public $this params ( $params ) | ||
$params | array |
依參數預留位置索引的查詢參數值列表。例如, |
回傳 | $this |
查詢物件本身 |
---|
public function params($params)
{
$this->params = $params;
return $this;
}
將原始查詢結果轉換為此查詢指定的格式。
此方法在內部用於將從資料庫擷取的資料轉換為此查詢所需的格式。
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);
}
定義於: 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;
}
準備建構 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;
}
透過先設定 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();
}
定義於: 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);
}
public string|integer|null|false scalar ( $db = null ) | ||
$db | yii\db\Connection|null |
用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 |
回傳 | string|integer|null|false |
查詢結果的第一列中第一個欄位的值。如果查詢結果為空,則傳回 False。 |
---|
public function scalar($db = null)
{
if ($this->emulateExecution) {
return null;
}
return $this->createCommand($db)->queryScalar();
}
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 物件的形式傳入。 請注意,如果您要選擇像 當欄位以陣列形式指定時,您也可以使用陣列鍵作為欄位別名 (如果欄位不需要別名,請不要使用字串鍵)。 從 2.0.1 版本開始,您還可以選擇子查詢作為欄位,方法是將每個這樣的欄位指定為代表子查詢的 |
$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;
}
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;
}
Defined in: yii\db\Query::sum()
回傳指定欄位值的總和。
public mixed sum ( $q, $db = null ) | ||
$q | string |
欄位名稱或運算式。請確保您已正確地 引用 運算式中的欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 陳述式的資料庫連線。如果未給定此參數,將使用 |
回傳 | mixed |
指定欄位值的總和。 |
---|
public function sum($q, $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->queryScalar("SUM($q)", $db);
}
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);
}
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;
}
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 回呼函式。其簽章應為 |
回傳 | $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;
}
為關聯式查詢指定連接資料表。
在 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 回呼函式。其簽章應為 |
回傳 | $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;
}
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;
}
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;
}
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;
}
註冊 或 登入 以進行評論。