類別 yii\db\Query
Query 以獨立於 DBMS 的方式表示 SELECT SQL 語句。
Query 提供了一組方法,以便於指定 SELECT 語句中的不同子句。這些方法可以鏈式調用。
透過調用 createCommand(),我們可以獲得一個 yii\db\Command 實例,該實例可以進一步用於對資料庫執行 DB 查詢。
例如,
$query = new Query;
// compose the query
$query->select('id, name')
->from('user')
->limit(10);
// build and execute the query
$rows = $query->all();
// alternatively, you can create DB command and execute it
$command = $query->createCommand();
// $command->sql returns the actual SQL
$rows = $command->queryAll();
Query 內部使用 yii\db\QueryBuilder 類別來產生 SQL 語句。
關於如何使用 Query 的更詳細指南,請參閱 Query Builder 指南文章。
公共屬性
公用方法
保護方法
方法 | 描述 | 定義於 |
---|---|---|
cleanUpTableNames() | 清除資料表名稱和別名。別名和名稱都括在 {{ 和 }} 中。 | yii\db\Query |
filterCondition() | 從給定的查詢條件中移除空運算元。 | yii\db\QueryTrait |
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\Query |
setCommandCache() | 設定 $command 快取 (如果此查詢已啟用快取)。 | yii\db\Query |
屬性詳細資料
是否僅選取不同的資料列。如果設定為 true,則 SELECT 子句會變更為 SELECT DISTINCT。
要从中選取的資料表。例如,['user', 'post']
。這用於建構 SQL 陳述式中的 FROM 子句。
另請參閱from()。
如何群組查詢結果。例如,['company', 'department']
。這用於建構 SQL 陳述式中的 GROUP BY 子句。
要套用在 GROUP BY 子句中的條件。它可以是字串或陣列。請參閱where(),以瞭解如何指定條件。
如何與其他資料表聯結。每個陣列元素都代表一個聯結的規格,其結構如下
[$joinType, $tableName, $joinCondition]
例如,
[
['INNER JOIN', 'user', 'user.id = author_id'],
['LEFT JOIN', 'team', 'team.id = team_id'],
]
與此查詢的快取查詢結果相關聯的相依性
另請參閱cache()。
查詢結果在快取中保持有效的預設秒數。使用 0 表示快取的資料永遠不會過期。使用負數表示不應使用查詢快取。使用布林值 true
表示應使用 yii\db\Connection::$queryCacheDuration。
另請參閱cache()。
正在選取的欄位。例如,['id', 'name']
。這用於建構 SQL 陳述式中的 SELECT 子句。如果未設定,則表示選取所有欄位。
另請參閱select()。
應附加到 'SELECT' 關鍵字的額外選項。例如,在 MySQL 中,可以使用選項 'SQL_CALC_FOUND_ROWS'。
這用於建構 SQL 陳述式中的 UNION 子句。每個陣列元素都是具有下列結構的陣列
query
:字串或 yii\db\Query 物件,代表查詢all
:布林值,指出應為UNION ALL
還是UNION
這用於建構 SQL 查詢中的 WITH 區段。每個陣列元素都是具有下列結構的陣列
query
:字串或 yii\db\Query 物件,代表查詢alias
:字串,查詢的別名,供進一步使用recursive
:布林值,指出應為WITH RECURSIVE
還是WITH
另請參閱withQuery()。
方法詳細資料
定義於: yii\base\Component::__call()
呼叫未作為類別方法的具名方法。
此方法將檢查是否有任何附加的行為具有具名方法,並在可用時執行該方法。
請勿直接呼叫此方法,因為它是 PHP magic 方法,當叫用不明方法時,將會隱含地呼叫此方法。
public mixed __call ( $name, $params ) | ||
$name | string |
方法名稱 |
$params | array |
方法參數 |
return | mixed |
方法傳回值 |
---|---|---|
throws | 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()");
}
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
定義於: yii\base\BaseObject::__construct()
建構子。
預設實作會執行兩件事
- 使用給定的組態
$config
初始化物件。 - 呼叫 init()。
如果子類別中覆寫此方法,建議
- 建構子的最後一個參數是組態陣列,例如此處的
$config
。 - 在建構子結尾呼叫父代實作。
public void __construct ( $config = [] ) | ||
$config | array |
將用於初始化物件屬性的名稱-值組 |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
定義於: yii\base\Component::__get()
傳回組件屬性的值。
此方法將依下列順序檢查並採取相應動作
- getter 定義的屬性:傳回 getter 結果
- 行為的屬性:傳回行為屬性值
請勿直接呼叫此方法,因為它是 PHP magic 方法,當執行 $value = $component->property;
時,將會隱含地呼叫此方法。
另請參閱 __set()。
public mixed __get ( $name ) | ||
$name | string |
屬性名稱 |
return | mixed |
屬性值或行為屬性的值 |
---|---|---|
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
throws | 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 magic 方法,當執行 isset($component->property)
時,將會隱含地呼叫此方法。
public boolean __isset ( $name ) | ||
$name | string |
屬性名稱或事件名稱 |
return | boolean |
具名屬性是否已設定 |
---|
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 magic 方法,當執行 $component->property = $value;
時,將會隱含地呼叫此方法。
另請參閱 __get()。
public void __set ( $name, $value ) | ||
$name | string |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
throws | yii\base\UnknownPropertyException |
如果未定義屬性 |
---|---|---|
throws | 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);
}
傳回 Query 的 SQL 表示法
public string __toString ( ) |
public function __toString()
{
return serialize($this);
}
定義於: yii\base\Component::__unset()
將組件屬性設定為 null。
此方法將依下列順序檢查並採取相應動作
- setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是 PHP magic 方法,當執行 unset($component->property)
時,將會隱含地呼叫此方法。
public void __unset ( $name ) | ||
$name | string |
屬性名稱 |
throws | 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);
}
將額外的 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 物件。 |
return | $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") 或陣列 (例如 此方法將自動引用欄位名稱,除非欄位包含括號(表示欄位包含資料庫運算式)。 請注意,如果您的 order-by 是包含逗號的運算式,您應始終使用陣列來表示 order-by 資訊。否則,此方法將無法正確判斷 order-by 欄位。 自 2.0.7 版本起,可以傳遞 yii\db\ExpressionInterface 物件,以純 SQL 語法明確指定 ORDER BY 部分。 |
return | $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;
}
新增要繫結至查詢的額外參數。
另請參閱 params()。
public $this addParams ( $params ) | ||
$params | array |
依參數預留位置索引的查詢參數值清單。例如, |
return | $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;
}
將更多欄位新增至查詢的 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()。 |
return | $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;
}
執行查詢並以陣列形式傳回所有結果。
public array all ( $db = null ) | ||
$db | yii\db\Connection|null |
用於產生 SQL 語句的資料庫連線。如果未提供此參數,將使用 |
return | array |
查詢結果。如果查詢沒有結果,將傳回空陣列。 |
---|
public function all($db = null)
{
if ($this->emulateExecution) {
return [];
}
$rows = $this->createCommand($db)->queryAll();
return $this->populate($rows);
}
為特定欄位新增篩選條件,並允許使用者選擇篩選運算子。
它為給定的欄位新增一個額外的 WHERE 條件,並根據給定值的前幾個字元判斷比較運算子。條件的加入方式與 andFilterWhere() 相同,因此 空值 會被忽略。新條件和現有條件將使用 AND
運算子結合。
比較運算子會根據給定值的前幾個字元智慧判斷。特別是,如果以下運算子作為給定值的開頭字元出現,則會被識別:
<
:欄位必須小於給定值。>
:欄位必須大於給定值。<=
:欄位必須小於或等於給定值。>=
:欄位必須大於或等於給定值。<>
:欄位不得與給定值相同。=
:欄位必須等於給定值。- 如果未偵測到上述任何運算子,將使用
$defaultOperator
。
public $this andFilterCompare ( $name, $value, $defaultOperator = '=' ) | ||
$name | string |
欄位名稱。 |
$value | string |
欄位值,可選擇在前面加上比較運算子。 |
$defaultOperator | string |
當 |
return | $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]);
}
將額外的 HAVING 條件新增至現有的條件,但忽略空運算元。
新條件和現有條件將使用 AND
運算子結合。
此方法與 andHaving() 類似。主要區別在於此方法將移除 空的查詢運算元。因此,此方法最適合用於根據使用者輸入的篩選值來建立查詢條件。
另請參閱
public array andFilterHaving ( array $condition ) | ||
$condition | array |
新的 HAVING 條件。請參閱 having() 以了解如何指定此參數。 |
return | $this |
查詢物件本身 |
---|
public function andFilterHaving(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->andHaving($condition);
}
return $this;
}
定義於: yii\db\QueryTrait::andFilterWhere()
將額外的 WHERE 條件新增至現有的條件,但忽略空運算元。
新條件和現有條件將使用 'AND' 運算子結合。
此方法與 andWhere() 類似。主要區別在於此方法將移除 空的查詢運算元。因此,此方法最適合用於根據使用者輸入的篩選值來建立查詢條件。
另請參閱
public $this andFilterWhere ( array $condition ) | ||
$condition | array |
新的 WHERE 條件。請參閱 where() 以了解如何指定此參數。 |
return | $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)。 |
return | $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 andWhere ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新的 WHERE 條件。請參閱 where() 以了解如何指定此參數。 |
$params | array |
要繫結到查詢的參數(name => value)。 |
return | $this |
查詢物件本身 |
---|
public function andWhere($condition, $params = [])
{
if ($this->where === null) {
$this->where = $condition;
} elseif (is_array($this->where) && isset($this->where[0]) && strcasecmp($this->where[0], 'and') === 0) {
$this->where[] = $condition;
} else {
$this->where = ['and', $this->where, $condition];
}
$this->addParams($params);
return $this;
}
定義於: yii\base\Component::attachBehavior()
將行為附加至此組件。
此方法將根據給定的組態建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法將行為物件附加到此組件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
行為的名稱。 |
$behavior | string|array|yii\base\Behavior |
行為組態。可以是下列其中之一:
|
return | yii\base\Behavior |
行為物件 |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
定義於: 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);
}
}
傳回指定欄位值的平均值。
public mixed average ( $q, $db = null ) | ||
$q | string |
欄位名稱或運算式。請確保在運算式中正確地 引用 欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 語句的資料庫連線。如果未提供此參數,將使用 |
return | mixed |
指定欄位值的平均值。 |
---|
public function average($q, $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->queryScalar("AVG($q)", $db);
}
啟動批次查詢。
批次查詢支援分批提取資料,這可以將記憶體使用量保持在限制之下。此方法將傳回 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" 應用程式組件。 |
return | 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,
]);
}
定義於: yii\base\Component::behaviors()
傳回此組件應表現為的行為清單。
子類別可以覆寫此方法,以指定它們想要表現為的行為。
此方法的傳回值應為行為物件或組態的陣列,並以行為名稱編製索引。行為組態可以是指定行為類別的字串,也可以是具有以下結構的陣列:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須繼承自 yii\base\Behavior。行為可以使用名稱或匿名方式附加。當使用名稱作為陣列鍵時,可以使用此名稱稍後使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。
在此方法中宣告的行為將自動(按需)附加到組件。
public array behaviors ( ) | ||
return | array |
行為組態。 |
---|
public function behaviors()
{
return [];
}
為此 Query 啟用查詢快取。
public $this cache ( $duration = true, $dependency = null ) | ||
$duration | integer|true |
查詢結果在快取中保持有效的秒數。使用 0 表示快取資料永不過期。使用負數表示不應使用查詢快取。使用布林值 |
$dependency | yii\caching\Dependency|null |
與快取結果相關聯的快取依賴性。 |
return | $this |
Query 物件本身 |
---|
public function cache($duration = true, $dependency = null)
{
$this->queryCacheDuration = $duration;
$this->queryCacheDependency = $dependency;
return $this;
}
定義於: yii\base\Component::canGetProperty()
傳回值,指出是否可以讀取屬性。
如果滿足以下條件,則可以讀取屬性:
- 類別具有與指定名稱關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可讀屬性(當
$checkBehaviors
為 true 時)。
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此組件的屬性 |
return | boolean |
屬性是否可以讀取 |
---|
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;
}
定義於: yii\base\Component::canSetProperty()
傳回值,指出是否可以設定屬性。
如果滿足以下條件,則可以寫入屬性:
- 類別具有與指定名稱關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可寫屬性(當
$checkBehaviors
為 true 時)。
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此組件的屬性 |
return | boolean |
屬性是否可以寫入 |
---|
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
。
定義於: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
清除資料表名稱和別名。別名和名稱都括在 {{ 和 }} 中。
protected string[] cleanUpTableNames ( $tableNames ) | ||
$tableNames | array |
非空陣列 |
return | 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;
}
執行查詢並傳回結果的第一欄。
public array column ( $db = null ) | ||
$db | yii\db\Connection|null |
用於產生 SQL 語句的資料庫連線。如果未提供此參數,將使用 |
return | 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;
}
傳回記錄數。
public integer|string|null count ( $q = '*', $db = null ) | ||
$q | string |
COUNT 運算式。預設為 '*'。請確保在運算式中正確地 引用 欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 語句的資料庫連線。如果未提供此參數(或為 null),將使用 |
return | integer|string|null |
記錄數。結果可能是字串,具體取決於底層資料庫引擎,並且為了支援高於 32 位元 PHP 整數可以處理的整數值。 |
---|
public function count($q = '*', $db = null)
{
if ($this->emulateExecution) {
return 0;
}
return $this->queryScalar("COUNT($q)", $db);
}
建立新的 Query 物件,並從現有物件複製其屬性值。
正在複製的屬性是查詢建構器要使用的屬性。
public static yii\db\Query create ( $from ) | ||
$from | yii\db\Query |
來源查詢物件 |
return | 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 |
用於產生 SQL 語句的資料庫連線。如果未提供此參數,將使用 |
return | yii\db\Command |
建立的 DB 命令實例。 |
---|
public function createCommand($db = null)
{
if ($db === null) {
$db = Yii::$app->getDb();
}
list($sql, $params) = $db->getQueryBuilder()->build($this);
$command = $db->createCommand($sql, $params);
$this->setCommandCache($command);
return $command;
}
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
行為的名稱。 |
return | 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;
}
定義於: yii\base\Component::detachBehaviors()
從組件卸離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
設定值,指出是否要 SELECT DISTINCT。
public $this distinct ( $value = true ) | ||
$value | boolean |
是否 SELECT DISTINCT。 |
return | $this |
查詢物件本身 |
---|
public function distinct($value = true)
{
$this->distinct = $value;
return $this;
}
啟動批次查詢並逐列擷取資料列。
此方法與 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" 應用程式組件。 |
return | 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,
]);
}
定義於: yii\db\QueryTrait::emulateExecution()
設定是否模擬查詢執行,防止與資料儲存互動。
在此模式啟用後,傳回查詢結果的方法,例如 yii\db\QueryInterface::one()、yii\db\QueryInterface::all()、yii\db\QueryInterface::exists() 等等,將會傳回空值或 false 值。當您的程式邏輯指示查詢不應傳回任何結果時,您應該使用此方法,例如在您設定類似 0=1
的 false where 條件時。
public $this emulateExecution ( $value = true ) | ||
$value | boolean |
是否阻止查詢執行。 |
return | $this |
查詢物件本身。 |
---|
public function emulateExecution($value = true)
{
$this->emulateExecution = $value;
return $this;
}
定義於: 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 語句的資料庫連線。如果未提供此參數,將使用 |
return | boolean |
查詢結果是否包含任何資料列。 |
---|
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 |
原始條件 |
return | array |
已移除空運算元的條件。 |
---|---|---|
throws | 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;
}
設定查詢的 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() 以了解如何指定此參數。 |
return | $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() 以了解如何指定此參數。 |
return | $this |
查詢物件本身 |
---|
public function filterWhere(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->where($condition);
}
return $this;
}
設定查詢的 FROM 部分。
public $this from ( $tables ) | ||
$tables | string|array|yii\db\ExpressionInterface |
要從中選取的表格。這可以是字串 (例如 當表格指定為陣列時,您也可以使用陣列鍵作為表格別名 (如果表格不需要別名,請勿使用字串鍵)。 使用 Query 物件來表示子查詢。在這種情況下,相應的陣列鍵將用作子查詢的別名。 若要以純 SQL 指定 以下是一些範例
|
return | $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 |
行為名稱 |
return | 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 ( ) | ||
return | yii\base\Behavior[] |
附加到此組件的行為列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
傳回在from()中使用的資料表名稱,依別名索引。
別名和名稱都包含在 {{ 和 }} 中。
public string[] getTablesUsedInFrom ( ) | ||
return | string[] |
以別名編製索引的表名 |
---|---|---|
throws | yii\base\InvalidConfigException |
public function getTablesUsedInFrom()
{
if (empty($this->from)) {
return [];
}
if (is_array($this->from)) {
$tableNames = $this->from;
} elseif (is_string($this->from)) {
$tableNames = preg_split('/\s*,\s*/', trim($this->from), -1, PREG_SPLIT_NO_EMPTY);
} elseif ($this->from instanceof Expression) {
$tableNames = [$this->from];
} else {
throw new InvalidConfigException(gettype($this->from) . ' in $from is not supported.');
}
return $this->cleanUpTableNames($tableNames);
}
protected array getUnaliasedColumnsFromSelect ( ) | ||
return | 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);
}
傳回唯一的欄位名稱,排除重複項。
要移除的欄位
- 如果欄位定義已存在於 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;
}
設定查詢的 GROUP BY 部分。
另請參閱 addGroupBy()。
public $this groupBy ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface|null |
要分組的欄位。欄位可以字串 (例如 "id, name") 或陣列 (例如 ['id', 'name']) 形式指定。除非欄位包含括號 (表示欄位包含資料庫運算式),否則此方法將自動為欄位名稱加上引號。 請注意,如果您的 group-by 是包含逗號的運算式,您應一律使用陣列來表示 group-by 資訊。否則,此方法將無法正確判斷 group-by 欄位。 自 2.0.7 版本起,可以傳遞 yii\db\ExpressionInterface 物件,以純 SQL 明確指定 GROUP BY 部分。自 2.0.14 版本起,也可以傳遞 yii\db\ExpressionInterface 物件。 |
return | $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 |
事件名稱 |
return | boolean |
是否有任何處理常式附加到事件。 |
---|
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 | boolean |
是否將行為的方法視為此組件的方法 |
return | boolean |
方法是否已定義 |
---|
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 | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為的屬性視為此組件的屬性 |
return | boolean |
屬性是否已定義 |
---|
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)。 |
return | $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 |
查詢結果應依據索引的欄位名稱。這也可以是一個可呼叫的物件 (例如匿名函式),根據給定的資料列資料傳回索引值。可呼叫物件的簽名應為
|
return | $this |
查詢物件本身 |
---|
public function indexBy($column)
{
$this->indexBy = $column;
return $this;
}
public void init ( ) |
public function init()
{
}
將 INNER JOIN 部分附加至查詢。
public $this innerJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
要聯接的表格或子查詢。 使用字串來表示要聯接的表格名稱。表格名稱可以包含結構描述字首 (例如 'public.user') 和/或表格別名 (例如 'user u')。除非表格名稱包含括號 (表示表格是以子查詢或資料庫運算式給定),否則此方法將自動為表格名稱加上引號。 您也可以將表格指定為包含一個元素的陣列,使用陣列鍵作為表格別名 (例如 ['u' => 'user'])。 若要聯接子查詢,請使用包含一個元素的陣列,將值設定為表示子查詢的 yii\db\Query 物件,並將對應的鍵表示別名。 |
$on | string|array |
應出現在 ON 部分的聯接條件。請參考 join() 以了解如何指定此參數。 |
$params | array |
要繫結到查詢的參數(name => value)。 |
return | $this |
查詢物件本身 |
---|
public function innerJoin($table, $on = '', $params = [])
{
$this->join[] = ['INNER JOIN', $table, $on];
return $this->addParams($params);
}
定義於: yii\db\QueryTrait::isEmpty()
傳回值,指出給定值是否為「空」。
如果滿足以下條件之一,則該值被視為「空」:
- 它是
null
, - 一個空字串 (
''
), - 一個僅包含空白字元的字串,
- 或一個空陣列。
protected boolean isEmpty ( $value ) | ||
$value | mixed | |
return | boolean |
如果值為空 |
---|
protected function isEmpty($value)
{
return $value === '' || $value === [] || $value === null || is_string($value) && trim($value) === '';
}
將 JOIN 部分附加至查詢。
第一個參數指定聯接的類型。
public $this join ( $type, $table, $on = '', $params = [] ) | ||
$type | string |
聯接的類型,例如 INNER JOIN、LEFT JOIN。 |
$table | string|array |
要聯接的表格或子查詢。 使用字串來表示要聯接的表格名稱。表格名稱可以包含結構描述字首 (例如 'public.user') 和/或表格別名 (例如 'user u')。除非表格名稱包含括號 (表示表格是以子查詢或資料庫運算式給定),否則此方法將自動為表格名稱加上引號。 您也可以將表格指定為包含一個元素的陣列,使用陣列鍵作為表格別名 (例如 ['u' => 'user'])。 若要聯接子查詢,請使用包含一個元素的陣列,將值設定為表示子查詢的 yii\db\Query 物件,並將對應的鍵表示別名。 |
$on | string|array |
應出現在 ON 部分的聯接條件。請參考 where() 以了解如何指定此參數。 請注意,where() 的陣列格式旨在將欄位與值而不是欄位與欄位匹配,因此以下內容將不會如預期般運作:
|
$params | array |
要繫結到查詢的參數(name => value)。 |
return | $this |
查詢物件本身 |
---|
public function join($type, $table, $on = '', $params = [])
{
$this->join[] = [$type, $table, $on];
return $this->addParams($params);
}
將 LEFT OUTER JOIN 部分附加至查詢。
public $this leftJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
要聯接的表格或子查詢。 使用字串來表示要聯接的表格名稱。表格名稱可以包含結構描述字首 (例如 'public.user') 和/或表格別名 (例如 'user u')。除非表格名稱包含括號 (表示表格是以子查詢或資料庫運算式給定),否則此方法將自動為表格名稱加上引號。 您也可以將表格指定為包含一個元素的陣列,使用陣列鍵作為表格別名 (例如 ['u' => 'user'])。 若要聯接子查詢,請使用包含一個元素的陣列,將值設定為表示子查詢的 yii\db\Query 物件,並將對應的鍵表示別名。 |
$on | string|array |
應出現在 ON 部分的聯接條件。請參考 join() 以了解如何指定此參數。 |
$params | array |
要綁定到查詢的參數 (name => value) |
return | $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 或負值來停用限制。 |
return | $this |
查詢物件本身 |
---|
public function limit($limit)
{
$this->limit = $limit;
return $this;
}
傳回指定欄位值的最大值。
public mixed max ( $q, $db = null ) | ||
$q | string |
欄位名稱或運算式。請確保在運算式中正確地 引用 欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 語句的資料庫連線。如果未提供此參數,將使用 |
return | mixed |
指定欄位值的最大值。 |
---|
public function max($q, $db = null)
{
return $this->queryScalar("MAX($q)", $db);
}
傳回指定欄位值的最小值。
public mixed min ( $q, $db = null ) | ||
$q | string |
欄位名稱或運算式。請確保在運算式中正確地 引用 欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 語句的資料庫連線。如果未提供此參數,將使用 |
return | mixed |
指定欄位值的最小值。 |
---|
public function min($q, $db = null)
{
return $this->queryScalar("MIN($q)", $db);
}
為此 Query 停用查詢快取。
public $this noCache ( ) | ||
return | $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;
}
正規化傳遞至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,則會移除附加到指定事件名稱的所有處理器。 |
return | boolean |
如果找到並分離處理器 |
---|
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 或負值停用偏移量。 |
return | $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 | boolean |
是否將新的事件處理器附加到現有處理器列表的末尾。如果為 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]);
}
}
執行查詢並傳回單一結果列。
public array|boolean one ( $db = null ) | ||
$db | yii\db\Connection|null |
用於產生 SQL 語句的資料庫連線。如果未提供此參數,將使用 |
return | array|boolean |
查詢結果的第一列(以陣列形式)。如果查詢結果為空,則傳回 False。 |
---|
public function one($db = null)
{
if ($this->emulateExecution) {
return false;
}
return $this->createCommand($db)->queryOne();
}
將額外的 HAVING 條件新增至現有的條件,但忽略空運算元。
新的條件和現有條件將使用 OR
運算子聯接。
此方法與 orHaving() 類似。主要區別在於此方法將移除空的查詢運算元。因此,此方法最適合根據使用者輸入的篩選值建立查詢條件。
另請參閱
public array orFilterHaving ( array $condition ) | ||
$condition | array |
新的 HAVING 條件。請參閱 having() 以了解如何指定此參數。 |
return | $this |
查詢物件本身 |
---|
public function orFilterHaving(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->orHaving($condition);
}
return $this;
}
定義於: yii\db\QueryTrait::orFilterWhere()
將額外的 WHERE 條件新增至現有的條件,但忽略空運算元。
新的條件和現有條件將使用 'OR' 運算子聯接。
此方法與 orWhere() 類似。主要區別在於此方法將移除空的查詢運算元。因此,此方法最適合根據使用者輸入的篩選值建立查詢條件。
另請參閱
public $this orFilterWhere ( array $condition ) | ||
$condition | array |
新的 WHERE 條件。請參閱 where() 以了解如何指定此參數。 |
return | $this |
查詢物件本身 |
---|
public function orFilterWhere(array $condition)
{
$condition = $this->filterCondition($condition);
if ($condition !== []) {
$this->orWhere($condition);
}
return $this;
}
public $this orHaving ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新的 HAVING 條件。請參閱 where() 以了解如何指定此參數。 |
$params | array |
要繫結到查詢的參數(name => value)。 |
return | $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 orWhere ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
新的 WHERE 條件。請參閱 where() 以了解如何指定此參數。 |
$params | array |
要繫結到查詢的參數(name => value)。 |
return | $this |
查詢物件本身 |
---|
public function orWhere($condition, $params = [])
{
if ($this->where === null) {
$this->where = $condition;
} else {
$this->where = ['or', $this->where, $condition];
}
$this->addParams($params);
return $this;
}
public $this orderBy ( $columns ) | ||
$columns | string|array|yii\db\ExpressionInterface|null |
要排序的欄位(和方向)。欄位可以字串形式(例如 此方法將自動引用欄位名稱,除非欄位包含括號(表示欄位包含資料庫運算式)。 請注意,如果您的 order-by 是包含逗號的運算式,您應始終使用陣列來表示 order-by 資訊。否則,此方法將無法正確判斷 order-by 欄位。 自 2.0.7 版本起,可以傳遞 yii\db\ExpressionInterface 物件,以純 SQL 語法明確指定 ORDER BY 部分。 |
return | $this |
查詢物件本身 |
---|
public function orderBy($columns)
{
$this->orderBy = $this->normalizeOrderBy($columns);
return $this;
}
設定要繫結至查詢的參數。
另請參閱 addParams()。
public $this params ( $params ) | ||
$params | array |
依參數預留位置索引的查詢參數值清單。例如, |
return | $this |
查詢物件本身 |
---|
public function params($params)
{
$this->params = $params;
return $this;
}
將原始查詢結果轉換為此查詢指定的格式。
此方法在內部用於將從資料庫擷取的資料轉換為此查詢所需的格式。
public array populate ( $rows ) | ||
$rows | array |
來自資料庫的原始查詢結果 |
return | array |
轉換後的查詢結果 |
---|
public function populate($rows)
{
if ($this->indexBy === null) {
return $rows;
}
$result = [];
foreach ($rows as $row) {
$result[ArrayHelper::getValue($row, $this->indexBy)] = $row;
}
return $result;
}
準備建置 SQL。
當 yii\db\QueryBuilder 開始從查詢物件建構 SQL 時,會呼叫此方法。您可以覆寫此方法,以在將查詢轉換為 SQL 陳述式時執行一些最終準備工作。
public $this prepare ( $builder ) | ||
$builder | yii\db\QueryBuilder | |
return | $this |
一個準備好的查詢實例,將由 yii\db\QueryBuilder 用於建構 SQL |
---|
public function prepare($builder)
{
return $this;
}
透過先設定select()來查詢純量值。
還原 select 的值,使此查詢可重複使用。
protected boolean|string|null queryScalar ( $selectExpression, $db ) | ||
$selectExpression | string|yii\db\ExpressionInterface | |
$db | yii\db\Connection|null |
用於執行查詢的資料庫連線。 |
throws | Throwable |
如果無法建立命令 |
---|
protected function queryScalar($selectExpression, $db)
{
if ($this->emulateExecution) {
return null;
}
if (
!$this->distinct
&& empty($this->groupBy)
&& empty($this->having)
&& empty($this->union)
) {
$select = $this->select;
$order = $this->orderBy;
$limit = $this->limit;
$offset = $this->offset;
$this->select = [$selectExpression];
$this->orderBy = null;
$this->limit = null;
$this->offset = null;
$e = null;
try {
$command = $this->createCommand($db);
} catch (\Exception $e) {
// throw it later (for PHP < 7.0)
} catch (\Throwable $e) {
// throw it later
}
$this->select = $select;
$this->orderBy = $order;
$this->limit = $limit;
$this->offset = $offset;
if ($e !== null) {
throw $e;
}
return $command->queryScalar();
}
$command = (new self())
->select([$selectExpression])
->from(['c' => $this])
->createCommand($db);
$this->setCommandCache($command);
return $command->queryScalar();
}
將 RIGHT OUTER JOIN 部分附加至查詢。
public $this rightJoin ( $table, $on = '', $params = [] ) | ||
$table | string|array |
要聯接的表格或子查詢。 使用字串來表示要聯接的表格名稱。表格名稱可以包含結構描述字首 (例如 'public.user') 和/或表格別名 (例如 'user u')。除非表格名稱包含括號 (表示表格是以子查詢或資料庫運算式給定),否則此方法將自動為表格名稱加上引號。 您也可以將表格指定為包含一個元素的陣列,使用陣列鍵作為表格別名 (例如 ['u' => 'user'])。 若要聯接子查詢,請使用包含一個元素的陣列,將值設定為表示子查詢的 yii\db\Query 物件,並將對應的鍵表示別名。 |
$on | string|array |
應出現在 ON 部分的聯接條件。請參考 join() 以了解如何指定此參數。 |
$params | array |
要綁定到查詢的參數 (name => value) |
return | $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 語句的資料庫連線。如果未提供此參數,將使用 |
return | string|integer|null|false |
查詢結果第一列的第一個欄位的值。如果查詢結果為空,則傳回 False。 |
---|
public function scalar($db = null)
{
if ($this->emulateExecution) {
return null;
}
return $this->createCommand($db)->queryScalar();
}
設定查詢的 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'。 |
return | $this |
查詢物件本身 |
---|
public function select($columns, $option = null)
{
$this->select = $this->normalizeSelect($columns);
$this->selectOption = $option;
return $this;
}
設定 $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;
}
傳回指定欄位值的總和。
public mixed sum ( $q, $db = null ) | ||
$q | string |
欄位名稱或運算式。請確保在運算式中正確地 引用 欄位名稱。 |
$db | yii\db\Connection|null |
用於產生 SQL 語句的資料庫連線。如果未提供此參數,將使用 |
return | 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);
}
使用 UNION 運算子附加 SQL 陳述式。
public $this union ( $sql, $all = false ) | ||
$sql | string|yii\db\Query |
要使用 UNION 附加的 SQL 陳述式 |
$all | boolean |
如果使用 UNION ALL 則為 TRUE,如果使用 UNION 則為 FALSE |
return | $this |
查詢物件本身 |
---|
public function union($sql, $all = false)
{
$this->union[] = ['query' => $sql, 'all' => $all];
return $this;
}
設定查詢的 WHERE 部分。
此方法需要 $condition
參數,以及選擇性的 $params
參數,用於指定要繫結到查詢的值。
$condition
參數應該是字串(例如 'id=1'
)或陣列。
{@inheritdoc}
另請參閱
public $this where ( $condition, $params = [] ) | ||
$condition | string|array|yii\db\ExpressionInterface |
應該放在 WHERE 部分的條件。 |
$params | array |
要繫結到查詢的參數(name => value)。 |
return | $this |
查詢物件本身 |
---|
public function where($condition, $params = [])
{
$this->where = $condition;
$this->addParams($params);
return $this;
}
使用 WITH 語法前置 SQL 陳述式。
public $this withQuery ( $query, $alias, $recursive = false ) | ||
$query | string|yii\db\Query |
要使用 WITH 前置的 SQL 陳述式 |
$alias | string |
WITH 建構中的查詢別名 |
$recursive | boolean |
如果使用 WITH RECURSIVE 則為 TRUE,如果使用 WITH 則為 FALSE |
return | $this |
查詢物件本身 |
---|
public function withQuery($query, $alias, $recursive = false)
{
$this->withQueries[] = ['query' => $query, 'alias' => $alias, 'recursive' => $recursive];
return $this;
}
註冊 或 登入 以進行評論。