類別 yii\db\Connection
繼承關係 | yii\db\Connection » yii\base\Component » yii\base\BaseObject |
---|---|
實作介面 | yii\base\Configurable |
自版本 | 2.0 |
原始碼 | https://github.com/yiisoft/yii2/blob/master/framework/db/Connection.php |
Connection 代表透過 PDO 連接到資料庫的連線。
Connection 與 yii\db\Command、yii\db\DataReader 和 yii\db\Transaction 協同工作,以在通用的 API 集中提供對各種 DBMS 的資料存取。它們是 PDO PHP 擴充套件 的輕薄封裝。
Connection 支援資料庫複製和讀寫分離。特別是,Connection 元件可以配置多個 主伺服器 和 從伺服器。它將透過選擇合適的伺服器來進行負載平衡和容錯移轉。它還將自動將讀取操作導向從伺服器,將寫入操作導向主伺服器。
要建立資料庫連線,請設定 $dsn、$username 和 $password,然後呼叫 open() 以連線到資料庫伺服器。可以使用 $isActive 檢查連線的目前狀態。
以下範例示範如何建立 Connection 實例並建立資料庫連線
$connection = new \yii\db\Connection([
'dsn' => $dsn,
'username' => $username,
'password' => $password,
]);
$connection->open();
建立資料庫連線後,可以執行如下的 SQL 語句
$command = $connection->createCommand('SELECT * FROM post');
$posts = $command->queryAll();
$command = $connection->createCommand('UPDATE post SET status=1');
$command->execute();
也可以執行預先處理的 SQL 並將參數繫結到預先處理的 SQL。當參數來自使用者輸入時,您應該使用這種方法來防止 SQL 注入攻擊。以下是一個範例
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
$command->bindValue(':id', $_GET['id']);
$post = $command->query();
有關如何執行各種資料庫查詢的更多資訊,請參閱 yii\db\Command。
如果底層 DBMS 支援事務,您可以執行如下的事務性 SQL 查詢
$transaction = $connection->beginTransaction();
try {
$connection->createCommand($sql1)->execute();
$connection->createCommand($sql2)->execute();
// ... executing other SQL statements ...
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
}
您也可以使用上面的簡寫形式,如下所示
$connection->transaction(function () {
$order = new Order($customer);
$order->save();
$order->addItems($items);
});
如果需要,您可以將事務隔離等級作為第二個參數傳遞
$connection->transaction(function (Connection $db) {
//return $db->...
}, Transaction::READ_UNCOMMITTED);
Connection 通常用作應用程式元件,並在應用程式配置中配置,如下所示
'components' => [
'db' => [
'class' => '\yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
],
],
公開屬性
Public Methods
Protected Methods
Method | 描述 | 定義於 |
---|---|---|
createPdoInstance() | 建立 PDO 實例。 | yii\db\Connection |
initConnection() | 初始化資料庫連線。 | yii\db\Connection |
openFromPool() | 從集區開啟伺服器的連線。 | yii\db\Connection |
openFromPoolSequentially() | 從集區開啟伺服器的連線。 | yii\db\Connection |
Events
Event | 類型 | 描述 | 定義於 |
---|---|---|---|
EVENT_AFTER_OPEN | yii\base\Event | 在建立資料庫連線後觸發的事件 | yii\db\Connection |
EVENT_BEGIN_TRANSACTION | yii\base\Event | 在頂層交易開始之前立即觸發的事件 | yii\db\Connection |
EVENT_COMMIT_TRANSACTION | yii\base\Event | 在頂層交易提交之後立即觸發的事件 | yii\db\Connection |
EVENT_ROLLBACK_TRANSACTION | yii\base\Event | 在頂層交易回滾之後立即觸發的事件 | yii\db\Connection |
Property Details
用於建立新的資料庫 yii\db\Command 物件的類別。如果您想擴充 yii\db\Command 類別,您可以配置此屬性以使用您擴充的版本。自 2.0.14 版本起,如果此屬性設定為預設值,則會使用 $commandMap。
另請參閱 createCommand()。
yii\db\Command 類別和 PDO 驅動程式名稱之間的對應。陣列的鍵是 PDO 驅動程式名稱,而值是相應的指令類別名稱或組態。請參閱 Yii::createObject(),以取得有關如何指定組態的詳細資訊。
此屬性主要由 createCommand() 用於建立新的資料庫 yii\db\Command 物件。除非您想使用自己的 yii\db\Command 類別或支援 Yii 不支援的 DBMS,否則通常不需要設定此屬性。
'pgsql' => 'yii\db\Command',
'mysqli' => 'yii\db\Command',
'mysql' => 'yii\db\Command',
'sqlite' => 'yii\db\sqlite\Command',
'sqlite2' => 'yii\db\sqlite\Command',
'sqlsrv' => 'yii\db\Command',
'oci' => 'yii\db\oci\Command',
'mssql' => 'yii\db\Command',
'dblib' => 'yii\db\Command',
'cubrid' => 'yii\db\Command',
]
資料庫驅動程式的名稱。請注意,此屬性的類型在 getter 和 setter 中有所不同。請參閱 getDriverName() 和 setDriverName() 以取得詳細資訊。
是否啟用預備陳述式模擬。預設為 false,表示 PDO 將在可用時使用原生預備支援。對於某些資料庫(例如 MySQL),可能需要將其設定為 true,以便 PDO 可以模擬預備支援,以繞過有錯誤的原生預備支援。預設值為 null,表示不會變更 PDO ATTR_EMULATE_PREPARES 值。
是否啟用資料庫查詢的記錄。預設為 true。如果您不需要記錄的資訊,您可能希望在生產環境中停用此選項以提高效能。
另請參閱 $enableProfiling。
是否啟用開啟資料庫連線和資料庫查詢的效能分析。預設為 true。如果您不需要記錄的資訊,您可能希望在生產環境中停用此選項以提高效能。
另請參閱 $enableLogging。
是否啟用查詢快取。請注意,為了啟用查詢快取,必須啟用由 $queryCache 指定的有效快取元件,且必須將 $enableQueryCache 設定為 true。此外,只有封閉在 cache() 中的查詢結果才會被快取。
另請參閱
是否啟用 儲存點。請注意,如果底層 DBMS 不支援儲存點,則將此屬性設定為 true 將沒有任何作用。
是否啟用結構描述快取。請注意,為了真正啟用結構描述快取,必須啟用由 $schemaCache 指定的有效快取元件,且必須將 $enableSchemaCache 設定為 true。
另請參閱
如果透過 pdo_dblib 連接的資料庫是 SyBase。
目前啟用的主要連線。如果沒有可用的主要連線,則傳回 null
。
應與 $masters 中列出的每個主要配置合併的配置。例如,
[
'username' => 'master',
'password' => 'master',
'attributes' => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
],
]
主要連線配置列表。每個配置都用於建立主要資料庫連線。當呼叫 open() 時,將選擇其中一個配置並用於建立此物件將使用的資料庫連線。請注意,當此屬性不為空時,此物件的連線設定(例如 "dsn"、"username")將被忽略。
另請參閱
自訂 PDO 包裝類別。如果未設定,則將在使用 MSSQL 時使用 PDO 或 yii\db\mssql\PDO。
另請參閱 $pdo。
目前資料庫連線的查詢建構器。請注意,此屬性的類型在 getter 和 setter 中有所不同。請參閱 getQueryBuilder() 和 setQueryBuilder() 以取得詳細資訊。
用於查詢快取的快取物件或快取應用程式元件的 ID。
另請參閱 $enableQueryCache。
查詢結果在快取中保持有效的預設秒數。預設值為 3600,表示 3600 秒或一小時。使用 0 表示快取資料永不過期。當呼叫 cache() 時未指定快取持續時間,將會使用此屬性的值。
另請參閱
用於快取資料表元資料的快取物件或快取應用程式元件的 ID。
另請參閱 $enableSchemaCache。
表格metadata在快取中保持有效的秒數。使用 0 表示快取資料永不過期。
另請參閱 $enableSchemaCache。
不應快取metadata的表格列表。預設為空陣列。表格名稱可以包含 schema 前綴(如果有的話)。請勿引用表格名稱。
另請參閱 $enableSchemaCache。
PDO 驅動程式名稱和 yii\db\Schema 類別之間的對應關係。陣列的鍵是 PDO 驅動程式名稱,而值是相應的 schema 類別名稱或組態。有關如何指定組態的詳細資訊,請參閱 Yii::createObject()。
此屬性主要由 getSchema() 在獲取資料庫 schema 資訊時使用。除非您想使用自己的 yii\db\Schema 類別來支援 Yii 不支援的 DBMS,否則通常不需要設定此屬性。
'pgsql' => 'yii\db\pgsql\Schema',
'mysqli' => 'yii\db\mysql\Schema',
'mysql' => 'yii\db\mysql\Schema',
'sqlite' => 'yii\db\sqlite\Schema',
'sqlite2' => 'yii\db\sqlite\Schema',
'sqlsrv' => 'yii\db\mssql\Schema',
'oci' => 'yii\db\oci\Schema',
'mssql' => 'yii\db\mssql\Schema',
'dblib' => 'yii\db\mssql\Schema',
'cubrid' => 'yii\db\cubrid\Schema',
]
$masters 和 $slaves 中列出的失效伺服器的重試間隔(秒)。這與 $serverStatusCache 一起使用。
快取物件或快取應用程式元件的 ID,用於儲存 $masters 和 $slaves 中指定的 DB 伺服器的健康狀態。僅當啟用讀寫分離或 $masters 不為空時才使用。設定布林值 false
以停用伺服器狀態快取。
另請參閱
- openFromPoolSequentially() 以取得有關容錯移轉行為的詳細資訊。
- $serverRetryInterval
目前作用中的 slave 連線。如果沒有可用的 slave 且 $fallbackToMaster
為 false,則傳回 null
。
應與 $slaves 中列出的每個 slave 組態合併的組態。例如,
[
'username' => 'slave',
'password' => 'slave',
'attributes' => [
// use a smaller connection timeout
PDO::ATTR_TIMEOUT => 10,
],
]
目前作用中 slave 連線的 PDO 實例。如果沒有可用的 slave 連線且 $fallbackToMaster
為 false,則傳回 null
。
slave 連線組態列表。每個組態都用於建立 slave DB 連線。當 $enableSlaves 為 true 時,將選擇其中一個組態並用於建立 DB 連線,僅執行讀取查詢。
另請參閱
表格名稱的通用前綴或後綴。如果表格名稱以 {{%TableName}}
形式給出,則百分比字元 %
將被此屬性值替換。例如,{{%post}}
變成 {{tbl_post}}
。
目前作用中的交易。如果沒有作用中的交易,則為 Null。
方法詳情
定義於: yii\base\Component::__call()
呼叫未定義為類別方法的具名方法。
此方法將檢查是否有任何附加的行為具有指定的名稱方法,如果有的話,將會執行它。
不要直接呼叫此方法,因為它是一個 PHP magic method,當呼叫未知方法時,它會被隱式呼叫。
public mixed __call ( $name, $params ) | ||
$name | 字串 |
方法名稱 |
$params | 陣列 |
方法參數 |
返回 | mixed |
方法返回值 |
---|---|---|
拋出 | yii\base\UnknownMethodException |
當呼叫未知方法時 |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
在複製後重設連線。
public void __clone ( ) |
public function __clone()
{
parent::__clone();
$this->_master = false;
$this->_slave = false;
$this->_schema = null;
$this->_transaction = null;
if (strncmp($this->dsn, 'sqlite::memory:', 15) !== 0) {
// reset PDO connection, unless its sqlite in-memory, which can only have one connection
$this->pdo = null;
}
}
定義於: yii\base\BaseObject::__construct()
建構子。
預設實作會做兩件事
- 使用給定的組態
$config
初始化物件。 - 呼叫 init()。
如果子類別中覆寫了此方法,建議
- 建構子的最後一個參數是一個組態陣列,就像這裡的
$config
一樣。 - 在建構子的結尾呼叫父類別實作。
public void __construct ( $config = [] ) | ||
$config | 陣列 |
將用於初始化物件屬性的名稱-值對 |
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
定義於: yii\base\Component::__get()
傳回元件屬性的值。
此方法將依以下順序檢查並相應地執行操作
- 由 getter 定義的屬性:返回 getter 結果
- 行為的屬性:返回行為屬性值
不要直接呼叫此方法,因為它是一個 PHP magic method,當執行 $value = $component->property;
時,它會被隱式呼叫。
另請參閱 __set()。
public mixed __get ( $name ) | ||
$name | 字串 |
屬性名稱 |
返回 | mixed |
屬性值或行為屬性的值 |
---|---|---|
拋出 | yii\base\UnknownPropertyException |
如果未定義屬性 |
拋出 | yii\base\InvalidCallException |
如果屬性是唯寫的。 |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
定義於: yii\base\Component::__isset()
檢查屬性是否已設定,即已定義且非 null。
此方法將依以下順序檢查並相應地執行操作
- 由 setter 定義的屬性:返回屬性是否已設定
- 行為的屬性:返回屬性是否已設定
- 對於不存在的屬性,返回
false
不要直接呼叫此方法,因為它是一個 PHP magic method,當執行 isset($component->property)
時,它會被隱式呼叫。
public boolean __isset ( $name ) | ||
$name | 字串 |
屬性名稱或事件名稱 |
返回 | 布林值 |
指定的名稱屬性是否已設定 |
---|
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 method,當執行 $component->property = $value;
時,它會被隱式呼叫。
另請參閱 __get()。
public void __set ( $name, $value ) | ||
$name | 字串 |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
拋出 | yii\base\UnknownPropertyException |
如果未定義屬性 |
---|---|---|
拋出 | yii\base\InvalidCallException |
如果屬性是唯讀的。 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
在序列化之前關閉連線。
public array __sleep ( ) |
public function __sleep()
{
$fields = (array) $this;
unset($fields['pdo']);
unset($fields["\000" . __CLASS__ . "\000" . '_master']);
unset($fields["\000" . __CLASS__ . "\000" . '_slave']);
unset($fields["\000" . __CLASS__ . "\000" . '_transaction']);
unset($fields["\000" . __CLASS__ . "\000" . '_schema']);
return array_keys($fields);
}
定義於: yii\base\Component::__unset()
將元件屬性設定為 null。
此方法將依以下順序檢查並相應地執行操作
- 由 setter 定義的屬性:將屬性值設定為 null
- 行為的屬性:將屬性值設定為 null
不要直接呼叫此方法,因為它是一個 PHP magic method,當執行 unset($component->property)
時,它會被隱式呼叫。
public void __unset ( $name ) | ||
$name | 字串 |
屬性名稱 |
拋出 | 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);
}
定義於: yii\base\Component::attachBehavior()
將行為附加到此元件。
此方法將基於給定的設定建立行為物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法將行為物件附加到此組件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | 字串 |
行為的名稱。 |
$behavior | string|array|yii\base\Behavior |
行為設定。這可以是下列其中之一
|
返回 | 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 | 陣列 |
要附加到組件的行為列表 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
開始一個交易。
public yii\db\Transaction beginTransaction ( $isolationLevel = null ) | ||
$isolationLevel | 字串|null |
用於此交易的隔離級別。 有關詳細信息,請參閱 yii\db\Transaction::begin()。 |
返回 | yii\db\Transaction |
啟動的交易 |
---|
public function beginTransaction($isolationLevel = null)
{
$this->open();
if (($transaction = $this->getTransaction()) === null) {
$transaction = $this->_transaction = new Transaction(['db' => $this]);
}
$transaction->begin($isolationLevel);
return $transaction;
}
定義於: yii\base\Component::behaviors()
傳回此元件應表現為的行為列表。
子類別可以覆寫此方法,以指定它們想要表現為的行為。
此方法的傳回值應為行為物件或設定的陣列,並以行為名稱索引。 行為設定可以是指定行為類別的字串,也可以是以下結構的陣列
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須從 yii\base\Behavior 擴展。 行為可以使用名稱或匿名方式附加。 當名稱用作陣列鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。 匿名行為無法檢索或分離。
在此方法中宣告的行為將自動(按需)附加到組件。
public array behaviors ( ) | ||
返回 | 陣列 |
行為設定。 |
---|
public function behaviors()
{
return [];
}
對可呼叫物件執行的查詢使用查詢快取。
當啟用查詢快取時($enableQueryCache 為 true 且 $queryCache 參照有效的快取),在可呼叫物件中執行的查詢將被快取,並且它們的結果將從快取中提取(如果可用)。 例如,
// The customer will be fetched from cache if available.
// If not, the query will be made against DB and cached for use next time.
$customer = $db->cache(function (Connection $db) {
return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});
請注意,查詢快取僅對傳回結果的查詢有意義。 對於使用 yii\db\Command::execute() 執行的查詢,將不會使用查詢快取。
另請參閱
public mixed cache ( callable $callable, $duration = null, $dependency = null ) | ||
$callable | 可呼叫 |
一個 PHP 可呼叫物件,其中包含將使用查詢快取的資料庫查詢。 可呼叫物件的簽名為 |
$duration | integer|null |
查詢結果可以在快取中保持有效的秒數。 如果未設定此值,則將改為使用 $queryCacheDuration 的值。 使用 0 表示快取資料永遠不會過期。 |
$dependency | yii\caching\Dependency|null |
與快取查詢結果相關聯的快取相依性。 |
返回 | mixed |
可呼叫物件的傳回結果 |
---|---|---|
拋出 | Throwable |
如果在查詢期間有任何例外 |
public function cache(callable $callable, $duration = null, $dependency = null)
{
$this->_queryCacheInfo[] = [$duration === null ? $this->queryCacheDuration : $duration, $dependency];
try {
$result = call_user_func($callable, $this);
array_pop($this->_queryCacheInfo);
return $result;
} catch (\Exception $e) {
array_pop($this->_queryCacheInfo);
throw $e;
} catch (\Throwable $e) {
array_pop($this->_queryCacheInfo);
throw $e;
}
}
定義於: yii\base\Component::canGetProperty()
傳回一個值,指示是否可以讀取屬性。
如果滿足以下任一條件,則可以讀取屬性
- 該類別具有與指定名稱關聯的 getter 方法(在這種情況下,屬性名稱不區分大小寫);
- 該類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可讀屬性(當
$checkBehaviors
為 true 時)。
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | 字串 |
屬性名稱 |
$checkVars | 布林值 |
是否將成員變數視為屬性 |
$checkBehaviors | 布林值 |
是否將行為的屬性視為此組件的屬性 |
返回 | 布林值 |
屬性是否可以讀取 |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
定義於: yii\base\Component::canSetProperty()
傳回一個值,指示是否可以設定屬性。
如果滿足以下任一條件,則可以寫入屬性
- 該類別具有與指定名稱關聯的 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 該類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的可寫屬性(當
$checkBehaviors
為 true 時)。
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | 字串 |
屬性名稱 |
$checkVars | 布林值 |
是否將成員變數視為屬性 |
$checkBehaviors | 布林值 |
是否將行為的屬性視為此組件的屬性 |
返回 | 布林值 |
屬性是否可以寫入 |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
。
定義於: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
返回 | 字串 |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
關閉目前啟用的資料庫連線。
如果連線已關閉,則此方法不執行任何操作。
public void close ( ) |
public function close()
{
if ($this->_master) {
if ($this->pdo === $this->_master->pdo) {
$this->pdo = null;
}
$this->_master->close();
$this->_master = false;
}
if ($this->pdo !== null) {
Yii::debug('Closing DB connection: ' . $this->dsn, __METHOD__);
$this->pdo = null;
}
if ($this->_slave) {
$this->_slave->close();
$this->_slave = false;
}
$this->_schema = null;
$this->_transaction = null;
$this->_driverName = null;
$this->_queryCacheInfo = [];
$this->_quotedTableNames = null;
$this->_quotedColumnNames = null;
}
建立要執行的指令。
public yii\db\Command createCommand ( $sql = null, $params = [] ) | ||
$sql | 字串|null |
要執行的 SQL 語句 |
$params | 陣列 |
要繫結到 SQL 語句的參數 |
返回 | yii\db\Command |
資料庫命令 |
---|
public function createCommand($sql = null, $params = [])
{
$driver = $this->getDriverName();
$config = ['class' => 'yii\db\Command'];
if ($this->commandClass !== $config['class']) {
$config['class'] = $this->commandClass;
} elseif (isset($this->commandMap[$driver])) {
$config = !is_array($this->commandMap[$driver]) ? ['class' => $this->commandMap[$driver]] : $this->commandMap[$driver];
}
$config['db'] = $this;
$config['sql'] = $sql;
/** @var Command $command */
$command = Yii::createObject($config);
return $command->bindValues($params);
}
建立 PDO 實例。
此方法由 open() 呼叫以建立資料庫連線。 預設實作將建立 PHP PDO 實例。 如果需要為特定 DBMS 改編預設 PDO,您可以覆寫此方法。
protected PDO createPdoInstance ( ) | ||
返回 | PDO |
pdo 實例 |
---|
protected function createPdoInstance()
{
$pdoClass = $this->pdoClass;
if ($pdoClass === null) {
$driver = null;
if ($this->_driverName !== null) {
$driver = $this->_driverName;
} elseif (($pos = strpos($this->dsn, ':')) !== false) {
$driver = strtolower(substr($this->dsn, 0, $pos));
}
switch ($driver) {
case 'mssql':
$pdoClass = 'yii\db\mssql\PDO';
break;
case 'dblib':
$pdoClass = 'yii\db\mssql\DBLibPDO';
break;
case 'sqlsrv':
$pdoClass = 'yii\db\mssql\SqlsrvPDO';
break;
default:
$pdoClass = 'PDO';
}
}
$dsn = $this->dsn;
if (strncmp('sqlite:@', $dsn, 8) === 0) {
$dsn = 'sqlite:' . Yii::getAlias(substr($dsn, 7));
}
return new $pdoClass($dsn, $this->username, $this->password, $this->attributes);
}
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | 字串 |
行為的名稱。 |
返回 | 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);
}
}
定義於: 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);
}
}
}
定義於: yii\base\Component::getBehavior()
傳回具名行為物件。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | 字串 |
行為名稱 |
返回 | yii\base\Behavior|null |
行為物件,如果行為不存在,則為 null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
定義於: yii\base\Component::getBehaviors()
傳回附加到此元件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
返回 | yii\base\Behavior[] |
附加到此組件的行為列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
傳回資料庫驅動程式的名稱。根據目前的 $dsn,如果最終使用者未明確設定。
public string|null getDriverName ( ) | ||
返回 | 字串|null |
資料庫驅動程式名稱 |
---|
public function getDriverName()
{
if ($this->_driverName === null) {
if (($pos = strpos((string)$this->dsn, ':')) !== false) {
$this->_driverName = strtolower(substr($this->dsn, 0, $pos));
} else {
$this->_driverName = strtolower($this->getSlavePdo(true)->getAttribute(PDO::ATTR_DRIVER_NAME));
}
}
return $this->_driverName;
}
傳回一個值,指示資料庫連線是否已建立。
public boolean getIsActive ( ) | ||
返回 | 布林值 |
資料庫連線是否已建立 |
---|
public function getIsActive()
{
return $this->pdo !== null;
}
傳回最後插入的列或序列值的 ID。
public string getLastInsertID ( $sequenceName = '' ) | ||
$sequenceName | 字串 |
序列物件的名稱(某些 DBMS 需要) |
返回 | 字串 |
最後插入的列 ID,或從序列物件檢索的最後一個值 |
---|
public function getLastInsertID($sequenceName = '')
{
return $this->getSchema()->getLastInsertID($sequenceName);
}
傳回目前啟用的主要連線。
如果第一次呼叫此方法,它將嘗試開啟主連線。
public yii\db\Connection|null getMaster ( ) | ||
返回 | yii\db\Connection|null |
目前啟用的主要連線。如果沒有可用的主要連線,則傳回 |
---|
public function getMaster()
{
if ($this->_master === false) {
$this->_master = $this->shuffleMasters
? $this->openFromPool($this->masters, $this->masterConfig)
: $this->openFromPoolSequentially($this->masters, $this->masterConfig);
}
return $this->_master;
}
傳回目前啟用的主要連線的 PDO 實例。
此方法將開啟主資料庫連線,然後傳回 $pdo。
public PDO getMasterPdo ( ) | ||
返回 | PDO |
目前啟用的主要連線的 PDO 實例。 |
---|
public function getMasterPdo()
{
$this->open();
return $this->pdo;
}
傳回目前資料庫連線的查詢建構器。
public yii\db\QueryBuilder getQueryBuilder ( ) | ||
返回 | yii\db\QueryBuilder |
目前資料庫連線的查詢建構器。 |
---|
public function getQueryBuilder()
{
return $this->getSchema()->getQueryBuilder();
}
傳回此連線開啟的資料庫的結構描述資訊。
public yii\db\Schema getSchema ( ) | ||
返回 | yii\db\Schema |
此連線開啟的資料庫的結構描述資訊。 |
---|---|---|
拋出 | yii\base\NotSupportedException |
如果目前驅動程式類型不受支援 |
public function getSchema()
{
if ($this->_schema !== null) {
return $this->_schema;
}
$driver = $this->getDriverName();
if (isset($this->schemaMap[$driver])) {
$config = !is_array($this->schemaMap[$driver]) ? ['class' => $this->schemaMap[$driver]] : $this->schemaMap[$driver];
$config['db'] = $this;
$this->_schema = Yii::createObject($config);
$this->restoreQueryBuilderConfiguration();
return $this->_schema;
}
throw new NotSupportedException("Connection does not support reading schema information for '$driver' DBMS.");
}
傳回伺服器版本,作為可透過 \version_compare() 比較的字串。
public string getServerVersion ( ) | ||
返回 | 字串 |
伺服器版本,以字串表示。 |
---|
public function getServerVersion()
{
return $this->getSchema()->getServerVersion();
}
傳回目前啟用的從屬連線。
如果第一次呼叫此方法,當 $enableSlaves 為 true 時,它將嘗試開啟從屬連線。
public yii\db\Connection|null getSlave ( $fallbackToMaster = true ) | ||
$fallbackToMaster | 布林值 |
如果沒有可用的從屬連線,是否傳回主連線。 |
返回 | yii\db\Connection|null |
目前作用中的 slave 連線。如果沒有可用的 slave 且 |
---|
public function getSlave($fallbackToMaster = true)
{
if (!$this->enableSlaves) {
return $fallbackToMaster ? $this : null;
}
if ($this->_slave === false) {
$this->_slave = $this->openFromPool($this->slaves, $this->slaveConfig);
}
return $this->_slave === null && $fallbackToMaster ? $this : $this->_slave;
}
傳回目前啟用的從屬連線的 PDO 實例。
當 $enableSlaves 為 true 時,其中一個從屬伺服器將用於讀取查詢,並且此方法將傳回其 PDO 實例。
public PDO|null getSlavePdo ( $fallbackToMaster = true ) | ||
$fallbackToMaster | 布林值 |
如果沒有可用的從屬連線,是否傳回主 PDO。 |
返回 | PDO|null |
目前作用中 slave 連線的 PDO 實例。如果沒有可用的 slave 連線且 |
---|
public function getSlavePdo($fallbackToMaster = true)
{
$db = $this->getSlave(false);
if ($db === null) {
return $fallbackToMaster ? $this->getMasterPdo() : null;
}
return $db->pdo;
}
取得具名資料表的結構描述資訊。
public yii\db\TableSchema|null getTableSchema ( $name, $refresh = false ) | ||
$name | 字串 |
資料表名稱。 |
$refresh | 布林值 |
即使在快取中找到資料表結構描述,是否仍重新載入。 |
返回 | yii\db\TableSchema|null |
資料表結構描述資訊。如果指定的資料表不存在,則為 Null。 |
---|
public function getTableSchema($name, $refresh = false)
{
return $this->getSchema()->getTableSchema($name, $refresh);
}
傳回目前啟用的交易。
public yii\db\Transaction|null getTransaction ( ) | ||
返回 | yii\db\Transaction|null |
目前作用中的交易。如果沒有作用中的交易,則為 Null。 |
---|
public function getTransaction()
{
return $this->_transaction && $this->_transaction->getIsActive() ? $this->_transaction : null;
}
定義於: yii\base\Component::hasEventHandlers()
傳回一個值,指示是否有任何處理常式附加到具名事件。
public boolean hasEventHandlers ( $name ) | ||
$name | 字串 |
事件名稱 |
返回 | 布林值 |
是否有任何處理常式附加到事件。 |
---|
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 | 字串 |
屬性名稱 |
$checkBehaviors | 布林值 |
是否將行為的方法視為此組件的方法 |
返回 | 布林值 |
方法是否已定義 |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
定義於: yii\base\Component::hasProperty()
傳回一個值,指示是否已為此元件定義屬性。
如果滿足以下任一條件,則定義屬性
- 該類別具有與指定名稱關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 該類別具有具有指定名稱的成員變數(當
$checkVars
為 true 時); - 附加的行為具有給定名稱的屬性(當
$checkBehaviors
為 true 時)。
另請參閱
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | 字串 |
屬性名稱 |
$checkVars | 布林值 |
是否將成員變數視為屬性 |
$checkBehaviors | 布林值 |
是否將行為的屬性視為此組件的屬性 |
返回 | 布林值 |
屬性是否已定義 |
---|
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()
{
}
初始化資料庫連線。
建立資料庫連線後立即調用此方法。 如果 $emulatePrepare 為 true,則預設實作會開啟 PDO::ATTR_EMULATE_PREPARES
,並設定資料庫 $charset(如果不為空)。 然後它會觸發 EVENT_AFTER_OPEN 事件。
protected void initConnection ( ) |
protected function initConnection()
{
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($this->emulatePrepare !== null && constant('PDO::ATTR_EMULATE_PREPARES')) {
if ($this->driverName !== 'sqlsrv') {
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, $this->emulatePrepare);
}
}
if (PHP_VERSION_ID >= 80100 && $this->getDriverName() === 'sqlite') {
$this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, true);
}
if (!$this->isSybase && in_array($this->getDriverName(), ['mssql', 'dblib'], true)) {
$this->pdo->exec('SET ANSI_NULL_DFLT_ON ON');
}
if ($this->charset !== null && in_array($this->getDriverName(), ['pgsql', 'mysql', 'mysqli', 'cubrid'], true)) {
$this->pdo->exec('SET NAMES ' . $this->pdo->quote($this->charset));
}
$this->trigger(self::EVENT_AFTER_OPEN);
}
暫時停用查詢快取。
在可調用物件中執行的查詢將完全不使用查詢快取。例如:
$db->cache(function (Connection $db) {
// ... queries that use query cache ...
return $db->noCache(function (Connection $db) {
// this query will not use query cache
return $db->createCommand('SELECT * FROM customer WHERE id=1')->queryOne();
});
});
另請參閱
public mixed noCache ( callable $callable ) | ||
$callable | 可呼叫 |
一個 PHP 可調用物件,其中包含不應使用查詢快取的資料庫查詢。此可調用物件的簽名為 |
返回 | mixed |
可呼叫物件的傳回結果 |
---|---|---|
拋出 | Throwable |
如果在查詢期間有任何例外 |
public function noCache(callable $callable)
{
$this->_queryCacheInfo[] = false;
try {
$result = call_user_func($callable, $this);
array_pop($this->_queryCacheInfo);
return $result;
} catch (\Exception $e) {
array_pop($this->_queryCacheInfo);
throw $e;
} catch (\Throwable $e) {
array_pop($this->_queryCacheInfo);
throw $e;
}
}
定義於: yii\base\Component::off()
從此元件分離現有的事件處理常式。
此方法與 on() 的作用相反。
注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理常式,而使用符合此萬用字元的純名稱註冊的處理常式將會保留。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | 字串 |
事件名稱 |
$handler | callable|null |
要移除的事件處理常式。如果為 null,則會移除附加到具名事件的所有處理常式。 |
返回 | 布林值 |
如果找到並分離處理常式 |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
將事件處理常式附加到事件。
事件處理常式必須是有效的 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 | 字串 |
事件名稱 |
$handler | 可呼叫 |
事件處理常式 |
$data | mixed |
在觸發事件時要傳遞給事件處理常式的資料。當調用事件處理常式時,可以透過 yii\base\Event::$data 存取此資料。 |
$append | 布林值 |
是否將新的事件處理常式附加到現有處理常式清單的末尾。如果為 false,則新的處理常式將插入到現有處理常式清單的開頭。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
建立資料庫連線。
如果已建立資料庫連線,則此方法不會執行任何操作。
public void open ( ) | ||
拋出 | yii\db\Exception |
如果連線失敗 |
---|
public function open()
{
if ($this->pdo !== null) {
return;
}
if (!empty($this->masters)) {
$db = $this->getMaster();
if ($db !== null) {
$this->pdo = $db->pdo;
return;
}
throw new InvalidConfigException('None of the master DB servers is available.');
}
if (empty($this->dsn)) {
throw new InvalidConfigException('Connection::dsn cannot be empty.');
}
$token = 'Opening DB connection: ' . $this->dsn;
$enableProfiling = $this->enableProfiling;
try {
if ($this->enableLogging) {
Yii::info($token, __METHOD__);
}
if ($enableProfiling) {
Yii::beginProfile($token, __METHOD__);
}
$this->pdo = $this->createPdoInstance();
$this->initConnection();
if ($enableProfiling) {
Yii::endProfile($token, __METHOD__);
}
} catch (\PDOException $e) {
if ($enableProfiling) {
Yii::endProfile($token, __METHOD__);
}
throw new Exception($e->getMessage(), $e->errorInfo, $e->getCode(), $e);
}
}
從集區開啟伺服器的連線。
此方法實作了在給定伺服器清單之間的負載平衡和容錯移轉。將以隨機順序嘗試連線。有關容錯移轉行為的詳細資訊,請參閱 openFromPoolSequentially()。
protected yii\db\Connection|null openFromPool ( array $pool, array $sharedConfig ) | ||
$pool | 陣列 |
伺服器池中連線組態的清單 |
$sharedConfig | 陣列 |
|
返回 | yii\db\Connection|null |
已開啟的資料庫連線,如果沒有可用的伺服器,則為 |
---|---|---|
拋出 | yii\base\InvalidConfigException |
如果組態未指定 "dsn" |
protected function openFromPool(array $pool, array $sharedConfig)
{
shuffle($pool);
return $this->openFromPoolSequentially($pool, $sharedConfig);
}
從集區開啟伺服器的連線。
此方法實作了在給定伺服器清單之間的容錯移轉。將依序嘗試連線。第一個成功的連線將會傳回。
如果配置了 $serverStatusCache,則此方法將快取有關無法連線伺服器的資訊,並且在 $serverRetryInterval 中配置的時間內不會嘗試連線到這些伺服器。這有助於在某些伺服器無法使用時保持應用程式穩定。避免嘗試連線到無法使用的伺服器可以節省連線嘗試因逾時而失敗的時間。
如果沒有任何伺服器可用,則會忽略狀態快取,並且會嘗試連線到所有伺服器(自 2.0.35 版本起)。這是為了避免在所有伺服器在短時間內都無法使用時發生停機。在成功連線後,伺服器會再次標記為可用。
另請參閱
protected yii\db\Connection|null openFromPoolSequentially ( array $pool, array $sharedConfig ) | ||
$pool | 陣列 |
伺服器池中連線組態的清單 |
$sharedConfig | 陣列 |
|
返回 | yii\db\Connection|null |
已開啟的資料庫連線,如果沒有可用的伺服器,則為 |
---|---|---|
拋出 | yii\base\InvalidConfigException |
如果組態未指定 "dsn" |
protected function openFromPoolSequentially(array $pool, array $sharedConfig)
{
if (empty($pool)) {
return null;
}
if (!isset($sharedConfig['class'])) {
$sharedConfig['class'] = get_class($this);
}
$cache = is_string($this->serverStatusCache) ? Yii::$app->get($this->serverStatusCache, false) : $this->serverStatusCache;
foreach ($pool as $i => $config) {
$pool[$i] = $config = array_merge($sharedConfig, $config);
if (empty($config['dsn'])) {
throw new InvalidConfigException('The "dsn" option must be specified.');
}
$key = [__METHOD__, $config['dsn']];
if ($cache instanceof CacheInterface && $cache->get($key)) {
// should not try this dead server now
continue;
}
/* @var $db Connection */
$db = Yii::createObject($config);
try {
$db->open();
return $db;
} catch (\Exception $e) {
Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
if ($cache instanceof CacheInterface) {
// mark this server as dead and only retry it after the specified interval
$cache->set($key, 1, $this->serverRetryInterval);
}
// exclude server from retry below
unset($pool[$i]);
}
}
if ($cache instanceof CacheInterface) {
// if server status cache is enabled and no server is available
// ignore the cache and try to connect anyway
// $pool now only contains servers we did not already try in the loop above
foreach ($pool as $config) {
/* @var $db Connection */
$db = Yii::createObject($config);
try {
$db->open();
} catch (\Exception $e) {
Yii::warning("Connection ({$config['dsn']}) failed: " . $e->getMessage(), __METHOD__);
continue;
}
// mark this server as available again after successful connection
$cache->delete([__METHOD__, $config['dsn']]);
return $db;
}
}
return null;
}
為在查詢中使用而引用資料行名稱。
如果資料行名稱包含前綴,前綴也會被正確地加上引號。如果資料行名稱已經加上引號或包含特殊字元,包括 '('、'[[' 和 '{{',則此方法將不執行任何操作。
public string quoteColumnName ( $name ) | ||
$name | 字串 |
資料行名稱 |
返回 | 字串 |
正確加上引號的資料行名稱 |
---|
public function quoteColumnName($name)
{
if (isset($this->_quotedColumnNames[$name])) {
return $this->_quotedColumnNames[$name];
}
return $this->_quotedColumnNames[$name] = $this->getSchema()->quoteColumnName($name);
}
透過引用雙括號括住的資料表和資料行名稱來處理 SQL 陳述式。
以雙大括號括起來的權杖被視為資料表名稱,而以雙方括號括起來的權杖被視為資料行名稱。它們將會相應地加上引號。此外,資料表名稱開頭或結尾的百分比字元 "%" 將會被 $tablePrefix 取代。
public string quoteSql ( $sql ) | ||
$sql | 字串 |
要加上引號的 SQL |
返回 | 字串 |
加上引號的 SQL |
---|
public function quoteSql($sql)
{
return preg_replace_callback(
'/(\\{\\{(%?[\w\-\. ]+%?)\\}\\}|\\[\\[([\w\-\. ]+)\\]\\])/',
function ($matches) {
if (isset($matches[3])) {
return $this->quoteColumnName($matches[3]);
}
return str_replace('%', $this->tablePrefix, $this->quoteTableName($matches[2]));
},
$sql
);
}
為在查詢中使用而引用資料表名稱。
如果資料表名稱包含結構描述前綴,前綴也會被正確地加上引號。如果資料表名稱已經加上引號或包含特殊字元,包括 '('、'[[' 和 '{{',則此方法將不執行任何操作。
public string quoteTableName ( $name ) | ||
$name | 字串 |
資料表名稱 |
返回 | 字串 |
正確加上引號的資料表名稱 |
---|
public function quoteTableName($name)
{
if (isset($this->_quotedTableNames[$name])) {
return $this->_quotedTableNames[$name];
}
return $this->_quotedTableNames[$name] = $this->getSchema()->quoteTableName($name);
}
public string quoteValue ( $value ) | ||
$value | 字串 |
要加上引號的字串 |
返回 | 字串 |
正確加上引號的字串 |
---|
public function quoteValue($value)
{
return $this->getSchema()->quoteValue($value);
}
變更目前的驅動程式名稱。
public void setDriverName ( $driverName ) | ||
$driverName | 字串 |
資料庫驅動程式名稱 |
public function setDriverName($driverName)
{
$this->_driverName = strtolower($driverName);
}
可用於透過連線配置陣列設定 yii\db\QueryBuilder 配置。
public void setQueryBuilder ( $value ) | ||
$value | 陣列 |
要配置的 yii\db\QueryBuilder 屬性。 |
public function setQueryBuilder($value)
{
Yii::configure($this->getQueryBuilder(), $value);
$this->_queryBuilderConfigurations[] = $value;
}
在交易中執行提供的回呼。
public mixed transaction ( callable $callback, $isolationLevel = null ) | ||
$callback | 可呼叫 |
執行工作的有效 PHP 回呼。接受連線實例作為參數。 |
$isolationLevel | 字串|null |
用於此交易的隔離級別。 有關詳細信息,請參閱 yii\db\Transaction::begin()。 |
返回 | mixed |
回呼函數的結果 |
---|---|---|
拋出 | Throwable |
如果在查詢期間有任何例外狀況。在這種情況下,交易將會回滾。 |
public function transaction(callable $callback, $isolationLevel = null)
{
$transaction = $this->beginTransaction($isolationLevel);
$level = $transaction->level;
try {
$result = call_user_func($callback, $this);
if ($transaction->isActive && $transaction->level === $level) {
$transaction->commit();
}
} catch (\Exception $e) {
$this->rollbackTransactionOnLevel($transaction, $level);
throw $e;
} catch (\Throwable $e) {
$this->rollbackTransactionOnLevel($transaction, $level);
throw $e;
}
return $result;
}
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | 字串 |
事件名稱 |
$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);
}
透過使用主要連線來執行提供的回呼。
提供此方法是為了讓您可以暫時強制使用主連線來執行資料庫操作,即使它們是讀取查詢。例如:
$result = $db->useMaster(function ($db) {
return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
});
public mixed useMaster ( callable $callback ) | ||
$callback | 可呼叫 |
此方法要執行的 PHP 可調用物件。其簽名為 |
返回 | mixed |
回呼的傳回值 |
---|---|---|
拋出 | Throwable |
如果回呼中拋出任何例外狀況 |
public function useMaster(callable $callback)
{
if ($this->enableSlaves) {
$this->enableSlaves = false;
try {
$result = call_user_func($callback, $this);
} catch (\Exception $e) {
$this->enableSlaves = true;
throw $e;
} catch (\Throwable $e) {
$this->enableSlaves = true;
throw $e;
}
// TODO: use "finally" keyword when miminum required PHP version is >= 5.5
$this->enableSlaves = true;
} else {
$result = call_user_func($callback, $this);
}
return $result;
}
事件詳細資訊
在建立資料庫連線後觸發的事件
在頂層交易開始之前立即觸發的事件
在頂層交易提交之後立即觸發的事件
在頂層交易回滾之後立即觸發的事件
註冊 或 登入 以進行評論。