類別 yii\db\Command
Command 代表一個 SQL 陳述式,將在資料庫中執行。
命令物件通常透過呼叫 yii\db\Connection::createCommand() 建立。它代表的 SQL 陳述式可以透過 $sql 屬性設定。
若要執行非查詢 SQL (例如 INSERT、DELETE、UPDATE),請呼叫 execute()。若要執行傳回結果資料集的 SQL 陳述式 (例如 SELECT),請使用 queryAll()、queryOne()、queryColumn()、queryScalar() 或 query()。
例如,
$users = $connection->createCommand('SELECT * FROM user')->queryAll();
Command 支援 SQL 陳述式預處理和參數綁定。呼叫 bindValue() 將值綁定到 SQL 參數;呼叫 bindParam() 將 PHP 變數綁定到 SQL 參數。當綁定參數時,SQL 陳述式會自動預處理。您也可以明確地呼叫 prepare() 來預處理 SQL 陳述式。
Command 也支援透過提供 insert()、update() 等方法來建構 SQL 陳述式。例如,以下程式碼將建立並執行 INSERT SQL 陳述式
$connection->createCommand()->insert('user', [
'name' => 'Sam',
'age' => 30,
])->execute();
若要建構 SELECT SQL 陳述式,請改用 yii\db\Query。
關於 Command 的更多詳細資訊和用法,請參閱關於資料庫存取物件的指南文章。
公開屬性
屬性 | 類型 | 描述 | 定義於 |
---|---|---|---|
$behaviors | yii\base\Behavior[] | 附加到此組件的行為列表。 | yii\base\Component |
$db | yii\db\Connection | 此命令關聯的資料庫連線 | yii\db\Command |
$fetchMode | integer | 此命令的預設提取模式。 | yii\db\Command |
$params | array | 綁定到目前 PDO 陳述式的參數 (名稱 => 值)。 | yii\db\Command |
$pdoStatement | PDOStatement | 此命令關聯的 PDOStatement 物件 | yii\db\Command |
$pendingParams | array | 待綁定到目前 PDO 陳述式的參數。 | yii\db\Command |
$queryCacheDependency | yii\caching\Dependency | 要與此命令的快取查詢結果關聯的依賴項 | yii\db\Command |
$queryCacheDuration | integer | 查詢結果在快取中保持有效的預設秒數。 | yii\db\Command |
$rawSql | string | 原始 SQL,參數值已插入到 $sql 中對應的佔位符。 | yii\db\Command |
$sql | string | 要執行的 SQL 陳述式。 | yii\db\Command |
公開方法
受保護的方法
方法 | 描述 | 定義於 |
---|---|---|
bindPendingParams() | 繫結透過 bindValue() 和 bindValues() 註冊的待處理參數。 | yii\db\Command |
getCacheKey() | 傳回查詢的快取鍵。 | yii\db\Command |
internalExecute() | 執行預先處理的陳述式。 | yii\db\Command |
logQuery() | 如果啟用了查詢記錄,則記錄目前的資料庫查詢,如果啟用了效能分析,則傳回效能分析權杖。 | yii\db\Command |
queryInternal() | 執行 SQL 陳述式的實際資料庫查詢。 | yii\db\Command |
refreshTableSchema() | 重新整理表格結構描述,該結構描述已由 requireTableSchemaRefresh() 標記。 | yii\db\Command |
requireTableSchemaRefresh() | 標記指定的表格結構描述在指令執行後重新整理。 | yii\db\Command |
requireTransaction() | 標記指令要在交易中執行。 | yii\db\Command |
reset() | 將指令屬性重設為其初始狀態。 | yii\db\Command |
setRetryHandler() | 設定在執行指令時擲回 yii\db\Exception 時呼叫的可呼叫物件(例如匿名函式)。可呼叫物件的簽章應為 | yii\db\Command |
屬性詳細資訊
此命令的預設提取模式。
另請參閱 https://php.dev.org.tw/manual/en/pdostatement.setfetchmode.php。
繫結到目前 PDO 陳述式的參數(名稱 => 值)。此屬性由 bindValue() 等方法維護。主要用於記錄目的,並用於產生 $rawSql。請勿直接修改它。
要與此命令的快取查詢結果關聯的依賴項
另請參閱 cache()。
查詢結果在快取中保持有效的預設秒數。使用 0 表示快取資料永遠不會過期。使用負數表示不應使用查詢快取。
另請參閱 cache()。
方法詳細資訊
定義於: yii\base\Component::__call()
呼叫指定的非類別方法。
此方法將檢查是否有任何附加的行為具有指定的名稱方法,如果有的話將會執行它。
不要直接呼叫此方法,因為它是一個 PHP 魔術方法,當呼叫未知方法時會隱式地被呼叫。
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 魔術方法,當執行 $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 魔術方法,當執行 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 魔術方法,當執行 $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);
}
定義於: yii\base\Component::__unset()
將元件屬性設定為 null。
此方法將依以下順序檢查並相應地執行動作
- 由 setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
不要直接呼叫此方法,因為它是一個 PHP 魔術方法,當執行 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);
}
建立 SQL 指令,用於為現有表格新增檢查約束。
public $this addCheck ( $name, $table, $expression ) | ||
$name | string |
檢查約束的名稱。名稱將由此方法正確地加上引號。 |
$table | string |
將在其中新增檢查約束的表格。名稱將由此方法正確地加上引號。 |
$expression | string |
`CHECK` 約束的 SQL。 |
return | $this |
命令物件本身。 |
---|
public function addCheck($name, $table, $expression)
{
$sql = $this->db->getQueryBuilder()->addCheck($name, $table, $expression);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於新增資料庫資料行。
public $this addColumn ( $table, $column, $type ) | ||
$table | string |
將在其中新增新資料行的表格。表格名稱將由此方法正確地加上引號。 |
$column | string |
新資料行的名稱。名稱將由此方法正確地加上引號。 |
$type | string |
資料行類型。將會呼叫 yii\db\QueryBuilder::getColumnType() 以將給定的資料行類型轉換為實體類型。例如, |
return | $this |
命令物件本身 |
---|
public function addColumn($table, $column, $type)
{
$sql = $this->db->getQueryBuilder()->addColumn($table, $column, $type);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於為資料行新增註解。
public $this addCommentOnColumn ( $table, $column, $comment ) | ||
$table | string |
要註解其資料行的表格。表格名稱將由此方法正確地加上引號。 |
$column | string |
要註解的資料行名稱。資料行名稱將由此方法正確地加上引號。 |
$comment | string |
要新增的註解文字。註解將由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function addCommentOnColumn($table, $column, $comment)
{
$sql = $this->db->getQueryBuilder()->addCommentOnColumn($table, $column, $comment);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於為表格新增註解。
public $this addCommentOnTable ( $table, $comment ) | ||
$table | string |
要註解其資料行的表格。表格名稱將由此方法正確地加上引號。 |
$comment | string |
要新增的註解文字。註解將由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function addCommentOnTable($table, $comment)
{
$sql = $this->db->getQueryBuilder()->addCommentOnTable($table, $comment);
return $this->setSql($sql);
}
建立 SQL 指令,用於為現有表格新增預設值約束。
public $this addDefaultValue ( $name, $table, $column, $value ) | ||
$name | string |
預設值約束的名稱。名稱將由此方法正確地加上引號。 |
$table | string |
將在其中新增預設值約束的表格。名稱將由此方法正確地加上引號。 |
$column | string |
約束將新增至的資料行名稱。名稱將由此方法正確地加上引號。 |
$value | mixed |
預設值。 |
return | $this |
命令物件本身。 |
---|
public function addDefaultValue($name, $table, $column, $value)
{
$sql = $this->db->getQueryBuilder()->addDefaultValue($name, $table, $column, $value);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於為現有表格新增外鍵約束。
此方法將正確地為表格和資料行名稱加上引號。
public $this addForeignKey ( $name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null ) | ||
$name | string |
外鍵約束的名稱。 |
$table | string |
外鍵約束將被加入的表格。 |
$columns | 字串|陣列 |
將約束加入的欄位名稱。如果有複數欄位,請用逗號分隔。 |
$refTable | string |
外鍵參考的表格。 |
$refColumns | 字串|陣列 |
外鍵參考的欄位名稱。如果有複數欄位,請用逗號分隔。 |
$delete | 字串|null |
ON DELETE 選項。大多數 DBMS 支援這些選項:RESTRICT、CASCADE、NO ACTION、SET DEFAULT、SET NULL |
$update | 字串|null |
ON UPDATE 選項。大多數 DBMS 支援這些選項:RESTRICT、CASCADE、NO ACTION、SET DEFAULT、SET NULL |
return | $this |
命令物件本身 |
---|
public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
{
$sql = $this->db->getQueryBuilder()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於為現有表格新增主鍵約束。
此方法將正確地為表格和資料行名稱加上引號。
public $this addPrimaryKey ( $name, $table, $columns ) | ||
$name | string |
主鍵約束的名稱。 |
$table | string |
主鍵約束將被加入的表格。 |
$columns | 字串|陣列 |
逗號分隔的字串或組成主鍵的欄位陣列。 |
return | $this |
命令物件本身。 |
---|
public function addPrimaryKey($name, $table, $columns)
{
$sql = $this->db->getQueryBuilder()->addPrimaryKey($name, $table, $columns);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於為現有表格新增唯一約束。
public $this addUnique ( $name, $table, $columns ) | ||
$name | string |
唯一性約束的名稱。名稱將會被此方法正確地加上引號。 |
$table | string |
唯一性約束將被加入的表格。名稱將會被此方法正確地加上引號。 |
$columns | 字串|陣列 |
將約束加入的欄位名稱。如果有複數欄位,請用逗號分隔。名稱將會被此方法正確地加上引號。 |
return | $this |
命令物件本身。 |
---|
public function addUnique($name, $table, $columns)
{
$sql = $this->db->getQueryBuilder()->addUnique($name, $table, $columns);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於變更資料行的定義。
public $this alterColumn ( $table, $column, $type ) | ||
$table | string |
要變更欄位的表格。表格名稱將會被此方法正確地加上引號。 |
$column | string |
要變更的欄位名稱。名稱將會被此方法正確地加上引號。 |
$type | string |
欄位類型。 yii\db\QueryBuilder::getColumnType() 將被呼叫,以將給定的欄位類型轉換為實體類型。例如, |
return | $this |
命令物件本身 |
---|
public function alterColumn($table, $column, $type)
{
$sql = $this->db->getQueryBuilder()->alterColumn($table, $column, $type);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
定義於: yii\base\Component::attachBehavior()
將一個行為附加到此元件。
此方法將根據給定的配置建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法,將行為物件附加到此組件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
行為的名稱。 |
$behavior | 字串|陣列|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);
}
}
建立批次 INSERT 指令。
例如,
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();
此方法將正確地逸出欄位名稱,並為要插入的值加上引號。
請注意,每列中的值必須與對應的欄位名稱匹配。
另請注意,建立的命令在 execute() 被呼叫之前不會執行。
public $this batchInsert ( $table, $columns, $rows ) | ||
$table | string |
新列將被插入的表格。 |
$columns | array |
欄位名稱 |
$rows | 陣列|Generator |
要批量插入到表格中的列 |
return | $this |
命令物件本身 |
---|
public function batchInsert($table, $columns, $rows)
{
$table = $this->db->quoteSql($table);
$columns = array_map(function ($column) {
return $this->db->quoteSql($column);
}, $columns);
$params = [];
$sql = $this->db->getQueryBuilder()->batchInsert($table, $columns, $rows, $params);
$this->setRawSql($sql);
$this->bindValues($params);
return $this;
}
定義於: 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 [];
}
將參數繫結到要執行的 SQL 陳述式。
另請參閱 https://php.dev.org.tw/manual/en/function.PDOStatement-bindParam.php。
public $this bindParam ( $name, &$value, $dataType = null, $length = null, $driverOptions = null ) | ||
$name | 字串|整數 |
參數識別符。對於使用具名佔位符的預處理語句,這將是 |
$value | mixed |
要綁定到 SQL 陳述式參數的 PHP 變數 (以引用傳遞) |
$dataType | 整數|null |
參數的 SQL 資料類型。如果為 null,則類型由值的 PHP 類型決定。 |
$length | 整數|null |
資料類型的長度 |
$driverOptions | mixed |
驅動程式特定的選項 |
return | $this |
目前正在執行的命令 |
---|
public function bindParam($name, &$value, $dataType = null, $length = null, $driverOptions = null)
{
$this->prepare();
if ($dataType === null) {
$dataType = $this->db->getSchema()->getPdoType($value);
}
if ($length === null) {
$this->pdoStatement->bindParam($name, $value, $dataType);
} elseif ($driverOptions === null) {
$this->pdoStatement->bindParam($name, $value, $dataType, $length);
} else {
$this->pdoStatement->bindParam($name, $value, $dataType, $length, $driverOptions);
}
$this->params[$name] = &$value;
return $this;
}
繫結透過 bindValue() 和 bindValues() 註冊的待處理參數。
請注意,此方法需要一個活動的 $pdoStatement。
protected void bindPendingParams ( ) |
protected function bindPendingParams()
{
foreach ($this->pendingParams as $name => $value) {
$this->pdoStatement->bindValue($name, $value[0], $value[1]);
}
$this->pendingParams = [];
}
public $this bindValue ( $name, $value, $dataType = null ) | ||
$name | 字串|整數 |
參數識別符。對於使用具名佔位符的預處理語句,這將是 |
$value | mixed |
要綁定到參數的值 |
$dataType | 整數|null |
參數的 SQL 資料類型。如果為 null,則類型由值的 PHP 類型決定。 |
return | $this |
目前正在執行的命令 |
---|
public function bindValue($name, $value, $dataType = null)
{
if ($dataType === null) {
$dataType = $this->db->getSchema()->getPdoType($value);
}
$this->pendingParams[$name] = [$value, $dataType];
$this->params[$name] = $value;
return $this;
}
將值列表繫結到對應的參數。
這與 bindValue() 類似,不同之處在於它一次綁定多個值。請注意,每個值的 SQL 資料類型由其 PHP 類型決定。
public $this bindValues ( $values ) | ||
$values | array |
要綁定的值。這必須以關聯陣列的形式給出,陣列鍵是參數名稱,陣列值是對應的參數值,例如 |
return | $this |
目前正在執行的命令 |
---|
public function bindValues($values)
{
if (empty($values)) {
return $this;
}
$schema = $this->db->getSchema();
foreach ($values as $name => $value) {
if (is_array($value)) { // TODO: Drop in Yii 2.1
$this->pendingParams[$name] = $value;
$this->params[$name] = $value[0];
} elseif ($value instanceof PdoValue) {
$this->pendingParams[$name] = [$value->getValue(), $value->getType()];
$this->params[$name] = $value->getValue();
} else {
if (version_compare(PHP_VERSION, '8.1.0') >= 0) {
if ($value instanceof \BackedEnum) {
$value = $value->value;
} elseif ($value instanceof \UnitEnum) {
$value = $value->name;
}
}
$type = $schema->getPdoType($value);
$this->pendingParams[$name] = [$value, $type];
$this->params[$name] = $value;
}
}
return $this;
}
為此指令啟用查詢快取。
public $this cache ( $duration = null, $dependency = null ) | ||
$duration | 整數|null |
此命令的查詢結果可以在快取中保持有效的秒數。如果未設定此值,則會改用 yii\db\Connection::$queryCacheDuration 的值。使用 0 表示快取資料永遠不會過期。 |
$dependency | yii\caching\Dependency|null |
與快取查詢結果相關聯的快取依賴性。 |
return | $this |
命令物件本身 |
---|
public function cache($duration = null, $dependency = null)
{
$this->queryCacheDuration = $duration === null ? $this->db->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;
}
取消 SQL 陳述式的執行。
此方法主要將 $pdoStatement 設定為 null。
public void cancel ( ) |
public function cancel()
{
$this->pdoStatement = null;
}
建立 SQL 指令,用於啟用或停用完整性檢查。
public $this checkIntegrity ( $check = true, $schema = '', $table = '' ) | ||
$check | boolean |
是否開啟或關閉完整性檢查。 |
$schema | string |
表格的結構描述名稱。預設為空字串,表示當前或預設結構描述。 |
$table | string |
表格名稱。 |
return | $this |
命令物件本身 |
---|---|---|
throws | yii\base\NotSupportedException |
如果底層 DBMS 不支援此功能 |
public function checkIntegrity($check = true, $schema = '', $table = '')
{
$sql = $this->db->getQueryBuilder()->checkIntegrity($check, $schema, $table);
return $this->setSql($sql);
}
::class
。
定義於: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
return | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
建立 SQL 指令,用於建立新的索引。
public $this createIndex ( $name, $table, $columns, $unique = false ) | ||
$name | string |
索引的名稱。名稱將會被此方法正確地加上引號。 |
$table | string |
將在其中建立新索引的表格。表格名稱將會被此方法正確地加上引號。 |
$columns | 字串|陣列 |
應該包含在索引中的欄位。如果有複數欄位,請用逗號分隔。欄位名稱將會被此方法正確地加上引號。 |
$unique | boolean |
是否在建立的索引上新增 UNIQUE 約束。 |
return | $this |
命令物件本身 |
---|
public function createIndex($name, $table, $columns, $unique = false)
{
$sql = $this->db->getQueryBuilder()->createIndex($name, $table, $columns, $unique);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於建立新的資料庫表格。
新表格中的欄位應該指定為名稱-定義配對 (例如 'name' => 'string'),其中 name 代表欄位名稱,將由方法正確地加上引號,而 definition 代表欄位類型,必須包含抽象 DB 類型。
方法 yii\db\QueryBuilder::getColumnType() 將被呼叫,以將抽象欄位類型轉換為實體類型。例如,string
將會被轉換為 varchar(255)
,而 string not null
則會變成 varchar(255) not null
。
如果僅使用定義指定欄位 (例如 'PRIMARY KEY (name, type)'),它將直接插入到產生的 SQL 中。
使用範例: `
php Yii::$app->db->createCommand()->createTable('post', [
'id' => 'pk',
'title' => 'string',
'text' => 'text',
'column_name double precision null default null',
]);
`
public $this createTable ( $table, $columns, $options = null ) | ||
$table | string |
要建立的表格名稱。名稱將會被此方法正確地加上引號。 |
$columns | array |
新表格中的欄位 (名稱 => 定義)。 |
$options | 字串|null |
將附加到產生的 SQL 的額外 SQL 片段。 |
return | $this |
命令物件本身 |
---|
public function createTable($table, $columns, $options = null)
{
$sql = $this->db->getQueryBuilder()->createTable($table, $columns, $options);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 視圖。
public $this createView ( $viewName, $subquery ) | ||
$viewName | string |
要建立的檢視表名稱。 |
$subquery | 字串|yii\db\Query |
定義檢視表的 SELECT 陳述式。這可以是字串或 yii\db\Query 物件。 |
return | $this |
命令物件本身。 |
---|
public function createView($viewName, $subquery)
{
$sql = $this->db->getQueryBuilder()->createView($viewName, $subquery);
return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
}
建立 DELETE 指令。
例如,
$connection->createCommand()->delete('user', 'status = 0')->execute();
或使用參數綁定作為條件
$status = 0;
$connection->createCommand()->delete('user', 'status = :status', [':status' => $status])->execute();
此方法將正確地逸出表格和欄位名稱。
請注意,建立的命令在 execute() 被呼叫之前不會執行。
public $this delete ( $table, $condition = '', $params = [] ) | ||
$table | string |
將從中刪除資料的表格。 |
$condition | 字串|陣列 |
將放在 WHERE 部分的條件。請參閱 yii\db\Query::where(),以了解如何指定條件。 |
$params | array |
要綁定到命令的參數 |
return | $this |
命令物件本身 |
---|
public function delete($table, $condition = '', $params = [])
{
$sql = $this->db->getQueryBuilder()->delete($table, $condition, $params);
return $this->setSql($sql)->bindValues($params);
}
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);
}
}
建立 SQL 指令,用於刪除檢查約束。
public $this dropCheck ( $name, $table ) | ||
$name | string |
要刪除的檢查約束名稱。名稱將會被此方法正確地加上引號。 |
$table | string |
要刪除檢查約束的表格。名稱將會被此方法正確地加上引號。 |
return | $this |
命令物件本身。 |
---|
public function dropCheck($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropCheck($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於刪除資料庫資料行。
public $this dropColumn ( $table, $column ) | ||
$table | string |
要刪除欄位的表格。名稱將會被此方法正確地加上引號。 |
$column | string |
要刪除的欄位名稱。名稱將會被此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function dropColumn($table, $column)
{
$sql = $this->db->getQueryBuilder()->dropColumn($table, $column);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於從資料行刪除註解。
public $this dropCommentFromColumn ( $table, $column ) | ||
$table | string |
要註解其資料行的表格。表格名稱將由此方法正確地加上引號。 |
$column | string |
要註解的資料行名稱。資料行名稱將由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function dropCommentFromColumn($table, $column)
{
$sql = $this->db->getQueryBuilder()->dropCommentFromColumn($table, $column);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於從表格刪除註解。
public $this dropCommentFromTable ( $table ) | ||
$table | string |
要註解其資料行的表格。表格名稱將由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function dropCommentFromTable($table)
{
$sql = $this->db->getQueryBuilder()->dropCommentFromTable($table);
return $this->setSql($sql);
}
建立 SQL 指令,用於刪除預設值約束。
public $this dropDefaultValue ( $name, $table ) | ||
$name | string |
要移除的預設值約束名稱。此名稱將會由此方法正確地加上引號。 |
$table | string |
要移除預設值約束的表格。此名稱將會由此方法正確地加上引號。 |
return | $this |
命令物件本身。 |
---|
public function dropDefaultValue($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropDefaultValue($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於刪除外鍵約束。
public $this dropForeignKey ( $name, $table ) | ||
$name | string |
要移除的外鍵約束名稱。此名稱將會由此方法正確地加上引號。 |
$table | string |
要移除外鍵的表格。此名稱將會由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function dropForeignKey($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropForeignKey($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於刪除索引。
public $this dropIndex ( $name, $table ) | ||
$name | string |
要移除的索引名稱。此名稱將會由此方法正確地加上引號。 |
$table | string |
要移除索引的表格。此名稱將會由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function dropIndex($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropIndex($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於從現有表格移除主鍵約束。
public $this dropPrimaryKey ( $name, $table ) | ||
$name | string |
要移除的主鍵約束名稱。 |
$table | string |
將從中移除主鍵約束的表格。 |
return | $this |
命令物件本身 |
---|
public function dropPrimaryKey($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropPrimaryKey($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於刪除資料庫表格。
public $this dropTable ( $table ) | ||
$table | string |
要移除的表格。此名稱將會由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function dropTable($table)
{
$sql = $this->db->getQueryBuilder()->dropTable($table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於刪除唯一約束。
public $this dropUnique ( $name, $table ) | ||
$name | string |
要移除的唯一性約束名稱。此名稱將會由此方法正確地加上引號。 |
$table | string |
要移除唯一性約束的表格。此名稱將會由此方法正確地加上引號。 |
return | $this |
命令物件本身。 |
---|
public function dropUnique($name, $table)
{
$sql = $this->db->getQueryBuilder()->dropUnique($name, $table);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
刪除 SQL 視圖。
public $this dropView ( $viewName ) | ||
$viewName | string |
要移除的檢視表名稱。 |
return | $this |
命令物件本身。 |
---|
public function dropView($viewName)
{
$sql = $this->db->getQueryBuilder()->dropView($viewName);
return $this->setSql($sql)->requireTableSchemaRefresh($viewName);
}
定義於: 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);
}
}
}
執行 SQL 陳述式。
此方法僅應用於執行非查詢 SQL 陳述式,例如 INSERT
、DELETE
、UPDATE
SQL。不會傳回任何結果集。
public integer execute ( ) | ||
return | integer |
受執行影響的列數。 |
---|---|---|
throws | yii\db\Exception |
執行失敗 |
public function execute()
{
$sql = $this->getSql();
list($profile, $rawSql) = $this->logQuery(__METHOD__);
if ($sql == '') {
return 0;
}
$this->prepare(false);
try {
$profile and Yii::beginProfile($rawSql, __METHOD__);
$this->internalExecute($rawSql);
$n = $this->pdoStatement->rowCount();
$profile and Yii::endProfile($rawSql, __METHOD__);
$this->refreshTableSchema();
return $n;
} catch (Exception $e) {
$profile and Yii::endProfile($rawSql, __METHOD__);
throw $e;
}
}
執行資料庫指令,重設表格主鍵的序列值。
執行的原因是某些資料庫 (Oracle) 需要多個查詢才能完成此操作。序列重設後,下一個插入新列的主鍵將具有指定的值或現有最大值 +1。
public void executeResetSequence ( $table, $value = null ) | ||
$table | string |
要重設主鍵序列的表格名稱 |
$value | mixed |
下一個插入新列的主鍵值。如果未設定,則下一個新列的主鍵將具有現有最大值 +1。 |
throws | yii\base\NotSupportedException |
如果底層 DBMS 不支援此功能 |
---|
public function executeResetSequence($table, $value = null)
{
return $this->db->getQueryBuilder()->executeResetSequence($table, $value);
}
定義於: 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;
}
傳回查詢的快取鍵。
protected array getCacheKey ( $method, $fetchMode, $rawSql ) | ||
$method | string |
要呼叫的 PDOStatement 方法 |
$fetchMode | integer |
結果提取模式。請參閱 PHP 手冊 以取得有效的提取模式。 |
$rawSql | ||
return | array |
快取鍵 |
---|
protected function getCacheKey($method, $fetchMode, $rawSql)
{
$params = $this->params;
ksort($params);
return [
__CLASS__,
$method,
$fetchMode,
$this->db->dsn,
$this->db->username,
$this->getSql(),
json_encode($params),
];
}
透過將參數值插入到 $sql 中對應的佔位符,傳回原始 SQL。
請注意,此方法的傳回值主要應用於記錄目的。此方法很可能由於參數佔位符的不當替換而傳回無效的 SQL。
public string getRawSql ( ) | ||
return | string |
原始 SQL,參數值已插入到 $sql 中對應的佔位符。 |
---|
public function getRawSql()
{
if (empty($this->params)) {
return $this->_sql;
}
$params = [];
foreach ($this->params as $name => $value) {
if (is_string($name) && strncmp(':', $name, 1)) {
$name = ':' . $name;
}
if (is_string($value) || $value instanceof Expression) {
$params[$name] = $this->db->quoteValue((string)$value);
} elseif (is_bool($value)) {
$params[$name] = ($value ? 'TRUE' : 'FALSE');
} elseif ($value === null) {
$params[$name] = 'NULL';
} elseif (!is_object($value) && !is_resource($value)) {
$params[$name] = $value;
}
}
if (!isset($params[1])) {
return preg_replace_callback('#(:\w+)#', function ($matches) use ($params) {
$m = $matches[1];
return isset($params[$m]) ? $params[$m] : $m;
}, $this->_sql);
}
$sql = '';
foreach (explode('?', $this->_sql) as $i => $part) {
$sql .= (isset($params[$i]) ? $params[$i] : '') . $part;
}
return $sql;
}
傳回此指令的 SQL 陳述式。
public string getSql ( ) | ||
return | string |
要執行的 SQL 陳述式 |
---|
public function getSql()
{
return $this->_sql;
}
定義於: 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 void init ( ) |
public function init()
{
}
建立 INSERT 指令。
例如,
$connection->createCommand()->insert('user', [
'name' => 'Sam',
'age' => 30,
])->execute();
此方法將正確地跳脫欄位名稱,並繫結要插入的值。
請注意,建立的命令在 execute() 被呼叫之前不會執行。
public $this insert ( $table, $columns ) | ||
$table | string |
新列將被插入的表格。 |
$columns | array|yii\db\Query |
要插入表格的欄位資料 (name => value) 或 Query 的實例,以執行 INSERT INTO ... SELECT SQL 陳述式。自版本 2.0.11 起,可以使用 Query 的傳遞。 |
return | $this |
命令物件本身 |
---|
public function insert($table, $columns)
{
$params = [];
$sql = $this->db->getQueryBuilder()->insert($table, $columns, $params);
return $this->setSql($sql)->bindValues($params);
}
執行預先處理的陳述式。
它是 \PDOStatement::execute() 的包裝函式,用於支援交易和重試處理常式。
protected void internalExecute ( $rawSql ) | ||
$rawSql | 字串|null |
如果已建立 rawSql。 |
throws | yii\db\Exception |
如果執行失敗。 |
---|
protected function internalExecute($rawSql)
{
$attempt = 0;
while (true) {
try {
if (
++$attempt === 1
&& $this->_isolationLevel !== false
&& $this->db->getTransaction() === null
) {
$this->db->transaction(function () use ($rawSql) {
$this->internalExecute($rawSql);
}, $this->_isolationLevel);
} else {
$this->pdoStatement->execute();
}
break;
} catch (\Exception $e) {
$rawSql = $rawSql ?: $this->getRawSql();
$e = $this->db->getSchema()->convertException($e, $rawSql);
if ($this->_retryHandler === null || !call_user_func($this->_retryHandler, $e, $attempt)) {
throw $e;
}
}
}
}
如果啟用了查詢記錄,則記錄目前的資料庫查詢,如果啟用了效能分析,則傳回效能分析權杖。
protected array logQuery ( $category ) | ||
$category | string |
記錄類別。 |
return | array |
包含兩個元素的陣列,第一個是布林值,表示是否啟用分析。第二個是已建立的 rawSql。 |
---|
protected function logQuery($category)
{
if ($this->db->enableLogging) {
$rawSql = $this->getRawSql();
Yii::info($rawSql, $category);
}
if (!$this->db->enableProfiling) {
return [false, isset($rawSql) ? $rawSql : null];
}
return [true, isset($rawSql) ? $rawSql : $this->getRawSql()];
}
為此指令停用查詢快取。
public $this noCache ( ) | ||
return | $this |
命令物件本身 |
---|
public function noCache()
{
$this->queryCacheDuration = -1;
return $this;
}
定義於: 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;
}
將事件處理常式附加到事件。
事件處理常式必須是有效的 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 | 可呼叫 |
事件處理常式 |
$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]);
}
}
準備要執行的 SQL 陳述式。
對於要多次執行的複雜 SQL 陳述式,這可能會提高效能。對於帶有繫結參數的 SQL 陳述式,將自動叫用此方法。
public void prepare ( $forRead = null ) | ||
$forRead | boolean|null |
此方法是否針對讀取查詢呼叫。如果為 null,則表示應使用 SQL 陳述式來判斷它是用於讀取還是寫入。 |
throws | yii\db\Exception |
如果有任何資料庫錯誤 |
---|
public function prepare($forRead = null)
{
if ($this->pdoStatement) {
$this->bindPendingParams();
return;
}
$sql = $this->getSql();
if ($sql === '') {
return;
}
if ($this->db->getTransaction()) {
// master is in a transaction. use the same connection.
$forRead = false;
}
if ($forRead || $forRead === null && $this->db->getSchema()->isReadQuery($sql)) {
$pdo = $this->db->getSlavePdo(true);
} else {
$pdo = $this->db->getMasterPdo();
}
try {
$this->pdoStatement = $pdo->prepare($sql);
$this->bindPendingParams();
} catch (\Exception $e) {
$message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
$errorInfo = $e instanceof \PDOException ? $e->errorInfo : null;
throw new Exception($message, $errorInfo, $e->getCode(), $e);
} catch (\Throwable $e) {
$message = $e->getMessage() . "\nFailed to prepare SQL: $sql";
throw new Exception($message, null, $e->getCode(), $e);
}
}
執行 SQL 陳述式並傳回查詢結果。
此方法用於執行傳回結果集的 SQL 查詢,例如 SELECT
。
public yii\db\DataReader query ( ) | ||
return | yii\db\DataReader |
用於擷取查詢結果的 reader 物件 |
---|---|---|
throws | yii\db\Exception |
執行失敗 |
public function query()
{
return $this->queryInternal('');
}
執行 SQL 陳述式並一次傳回所有列。
public array queryAll ( $fetchMode = null ) | ||
$fetchMode | 整數|null |
結果提取模式。請參考 PHP 手冊 以了解有效的提取模式。如果此參數為 null,將會使用 $fetchMode 中設定的值。 |
return | array |
查詢結果的所有列。每個陣列元素都是一個代表資料列的陣列。如果查詢結果為空,則會傳回一個空陣列。 |
---|---|---|
throws | yii\db\Exception |
執行失敗 |
public function queryAll($fetchMode = null)
{
return $this->queryInternal('fetchAll', $fetchMode);
}
執行 SQL 陳述式並傳回結果的第一個資料行。
當查詢只需要結果的第一個欄位(即每一列中的第一個元素)時,最適合使用此方法。
public array queryColumn ( ) | ||
return | array |
查詢結果的第一個欄位。如果查詢結果為空,則傳回空陣列。 |
---|---|---|
throws | yii\db\Exception |
執行失敗 |
public function queryColumn()
{
return $this->queryInternal('fetchAll', \PDO::FETCH_COLUMN);
}
執行 SQL 陳述式的實際資料庫查詢。
protected mixed queryInternal ( $method, $fetchMode = null ) | ||
$method | string |
要呼叫的 PDOStatement 方法 |
$fetchMode | 整數|null |
結果提取模式。請參考 PHP 手冊 以了解有效的提取模式。如果此參數為 null,將會使用 $fetchMode 中設定的值。 |
return | mixed |
方法執行結果 |
---|---|---|
throws | yii\db\Exception |
如果查詢導致任何問題 |
版本 | 描述 |
---|---|
2.0.1 | 此方法為 protected (之前為 private)。 |
protected function queryInternal($method, $fetchMode = null)
{
list($profile, $rawSql) = $this->logQuery('yii\db\Command::query');
if ($method !== '') {
$info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
if (is_array($info)) {
/* @var $cache \yii\caching\CacheInterface */
$cache = $info[0];
$cacheKey = $this->getCacheKey($method, $fetchMode, '');
$result = $cache->get($cacheKey);
if (is_array($result) && array_key_exists(0, $result)) {
Yii::debug('Query result served from cache', 'yii\db\Command::query');
return $result[0];
}
}
}
$this->prepare(true);
try {
$profile and Yii::beginProfile($rawSql, 'yii\db\Command::query');
$this->internalExecute($rawSql);
if ($method === '') {
$result = new DataReader($this);
} else {
if ($fetchMode === null) {
$fetchMode = $this->fetchMode;
}
$result = call_user_func_array([$this->pdoStatement, $method], (array) $fetchMode);
$this->pdoStatement->closeCursor();
}
$profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
} catch (Exception $e) {
$profile and Yii::endProfile($rawSql, 'yii\db\Command::query');
throw $e;
}
if (isset($cache, $cacheKey, $info)) {
$cache->set($cacheKey, [$result], $info[1], $info[2]);
Yii::debug('Saved query result in cache', 'yii\db\Command::query');
}
return $result;
}
執行 SQL 陳述式並傳回結果的第一列。
當查詢只需要結果的第一列時,最適合使用此方法。
public array|false queryOne ( $fetchMode = null ) | ||
$fetchMode | 整數|null |
結果提取模式。請參考 PHP 手冊 以了解有效的提取模式。如果此參數為 null,將會使用 $fetchMode 中設定的值。 |
return | array|false |
查詢結果的第一列(以陣列形式)。如果查詢結果為空,則傳回 False。 |
---|---|---|
throws | yii\db\Exception |
執行失敗 |
public function queryOne($fetchMode = null)
{
return $this->queryInternal('fetch', $fetchMode);
}
執行 SQL 陳述式並傳回資料第一列中第一個資料行的值。
當查詢只需要單一值時,最適合使用此方法。
public string|integer|null|false queryScalar ( ) | ||
return | string|integer|null|false |
查詢結果的第一列中第一個欄位的值。如果沒有值,則傳回 False。 |
---|---|---|
throws | yii\db\Exception |
執行失敗 |
public function queryScalar()
{
$result = $this->queryInternal('fetchColumn', 0);
if (is_resource($result) && get_resource_type($result) === 'stream') {
return stream_get_contents($result);
}
return $result;
}
重新整理表格結構描述,該結構描述已由 requireTableSchemaRefresh() 標記。
protected void refreshTableSchema ( ) |
protected function refreshTableSchema()
{
if ($this->_refreshTableName !== null) {
$this->db->getSchema()->refreshTableSchema($this->_refreshTableName);
}
}
建立 SQL 指令,用於重新命名資料行。
public $this renameColumn ( $table, $oldName, $newName ) | ||
$table | string |
要重新命名的欄位所屬的資料表。資料表名稱將會由此方法正確地加上引號。 |
$oldName | string |
欄位的舊名稱。名稱將會由此方法正確地加上引號。 |
$newName | string |
欄位的新名稱。名稱將會由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function renameColumn($table, $oldName, $newName)
{
$sql = $this->db->getQueryBuilder()->renameColumn($table, $oldName, $newName);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
建立 SQL 指令,用於重新命名資料庫表格。
public $this renameTable ( $table, $newName ) | ||
$table | string |
要重新命名的資料表。資料表名稱將會由此方法正確地加上引號。 |
$newName | string |
資料表的新名稱。名稱將會由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function renameTable($table, $newName)
{
$sql = $this->db->getQueryBuilder()->renameTable($table, $newName);
return $this->setSql($sql)->requireTableSchemaRefresh($table);
}
標記指定的表格結構描述在指令執行後重新整理。
protected $this requireTableSchemaRefresh ( $name ) | ||
$name | string |
應重新整理結構描述的資料表名稱。 |
return | $this |
此 command 實例 |
---|
protected function requireTableSchemaRefresh($name)
{
$this->_refreshTableName = $name;
return $this;
}
標記指令要在交易中執行。
protected $this requireTransaction ( $isolationLevel = null ) | ||
$isolationLevel | 字串|null |
用於此交易的隔離等級。請參閱 yii\db\Transaction::begin() 以了解詳細資訊。 |
return | $this |
此 command 實例。 |
---|
protected function requireTransaction($isolationLevel = null)
{
$this->_isolationLevel = $isolationLevel;
return $this;
}
將指令屬性重設為其初始狀態。
protected void reset ( ) |
protected function reset()
{
$this->_sql = null;
$this->pendingParams = [];
$this->params = [];
$this->_refreshTableName = null;
$this->_isolationLevel = false;
}
建立 SQL 指令,用於重設表格主鍵的序列值。
序列將會被重設,使得下一個插入的新列的主鍵將會具有指定的值或現有最大值 +1。
public $this resetSequence ( $table, $value = null ) | ||
$table | string |
將重設其主鍵序列的資料表名稱 |
$value | mixed |
下一個插入新列的主鍵值。如果未設定,則下一個新列的主鍵將具有現有最大值 +1。 |
return | $this |
命令物件本身 |
---|---|---|
throws | yii\base\NotSupportedException |
如果底層 DBMS 不支援此功能 |
public function resetSequence($table, $value = null)
{
$sql = $this->db->getQueryBuilder()->resetSequence($table, $value);
return $this->setSql($sql);
}
public $this setRawSql ( $sql ) | ||
$sql | string |
要設定的 SQL 陳述式。 |
return | $this |
此 command 實例 |
---|
public function setRawSql($sql)
{
if ($sql !== $this->_sql) {
$this->cancel();
$this->reset();
$this->_sql = $sql;
}
return $this;
}
設定在執行指令時擲回 yii\db\Exception 時呼叫的可呼叫物件(例如匿名函式)。可呼叫物件的簽章應為
function (\yii\db\Exception $e, $attempt)
{
// return true or false (whether to retry the command or rethrow $e)
}
此可呼叫物件將會接收一個擲出的資料庫例外,以及當前嘗試 (執行 command) 次數,從 1 開始。
protected callable setRetryHandler ( callable $handler ) | ||
$handler | 可呼叫 |
一個 PHP 回呼函式,用於處理資料庫例外。 |
return | $this |
此 command 實例。 |
---|
protected function setRetryHandler(callable $handler)
{
$this->_retryHandler = $handler;
return $this;
}
指定要執行的 SQL 陳述式。SQL 陳述式將使用 yii\db\Connection::quoteSql() 加上引號。
先前的 SQL (如果有的話) 將會被捨棄,並且 $params 也會被清除。請參閱 reset() 以了解詳細資訊。
參見
public $this setSql ( $sql ) | ||
$sql | string |
要設定的 SQL 陳述式。 |
return | $this |
此 command 實例 |
---|
public function setSql($sql)
{
if ($sql !== $this->_sql) {
$this->cancel();
$this->reset();
$this->_sql = $this->db->quoteSql($sql);
}
return $this;
}
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);
}
建立 SQL 指令,用於截斷資料庫表格。
public $this truncateTable ( $table ) | ||
$table | string |
要清空的資料表。資料表名稱將會由此方法正確地加上引號。 |
return | $this |
命令物件本身 |
---|
public function truncateTable($table)
{
$sql = $this->db->getQueryBuilder()->truncateTable($table);
return $this->setSql($sql);
}
建立 UPDATE 指令。
例如,
$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
或使用參數綁定作為條件
$minAge = 30;
$connection->createCommand()->update('user', ['status' => 1], 'age > :minAge', [':minAge' => $minAge])->execute();
此方法將會正確地跳脫欄位名稱,並綁定要更新的值。
請注意,建立的命令在 execute() 被呼叫之前不會執行。
public $this update ( $table, $columns, $condition = '', $params = [] ) | ||
$table | string |
要更新的資料表。 |
$columns | array |
要更新的欄位資料 (name => value)。 |
$condition | 字串|陣列 |
將放在 WHERE 部分的條件。請參閱 yii\db\Query::where(),以了解如何指定條件。 |
$params | array |
要綁定到命令的參數 |
return | $this |
命令物件本身 |
---|
public function update($table, $columns, $condition = '', $params = [])
{
$sql = $this->db->getQueryBuilder()->update($table, $columns, $condition, $params);
return $this->setSql($sql)->bindValues($params);
}
建立一個指令,用於將列插入到資料庫表格中(如果它們尚不存在,則比對唯一約束),或者如果它們存在則更新它們。
例如,
$sql = $queryBuilder->upsert('pages', [
'name' => 'Front page',
'url' => 'https://example.com/', // url is unique
'visits' => 0,
], [
'visits' => new \yii\db\Expression('visits + 1'),
], $params);
此方法將正確地逸出表格和欄位名稱。
public $this upsert ( $table, $insertColumns, $updateColumns = true, $params = [] ) | ||
$table | string |
新列將插入/更新至的資料表。 |
$insertColumns | array|yii\db\Query |
要插入資料表中的欄位資料 (name => value),或是要執行 |
$updateColumns | array|boolean |
如果欄位資料已存在,則要更新的欄位資料 (name => value)。如果傳遞 |
$params | array |
要綁定到 command 的參數。 |
return | $this |
命令物件本身。 |
---|
public function upsert($table, $insertColumns, $updateColumns = true, $params = [])
{
$sql = $this->db->getQueryBuilder()->upsert($table, $insertColumns, $updateColumns, $params);
return $this->setSql($sql)->bindValues($params);
}
註冊 或 登入 以進行評論。