0 追蹤者

類別 yii\db\Transaction

繼承關係yii\db\Transaction » yii\base\BaseObject
實作yii\base\Configurable
自版本起可用2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/db/Transaction.php

Transaction 代表一個資料庫交易。

它通常通過呼叫 yii\db\Connection::beginTransaction() 來建立。

以下程式碼是使用交易的典型範例 (請注意,某些 DBMS 可能不支援交易)

$transaction = $connection->beginTransaction();
try {
    $connection->createCommand($sql1)->execute();
    $connection->createCommand($sql2)->execute();
    //.... other SQL executions
    $transaction->commit();
} catch (\Exception $e) {
    $transaction->rollBack();
    throw $e;
} catch (\Throwable $e) {
    $transaction->rollBack();
    throw $e;
}

注意:在上面的程式碼中,我們有兩個 catch 區塊,以與 PHP 5.x 和 PHP 7.x 相容。\Exception 實現了 \Throwable 介面 自 PHP 7.0 起,因此如果您的應用程式僅使用 PHP 7.0 及更高版本,則可以跳過包含 \Exception 的部分。

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$db yii\db\Connection 此交易關聯的資料庫連線。 yii\db\Transaction
$isActive boolean 此交易是否為活動狀態。 yii\db\Transaction
$isolationLevel string 用於此交易的交易隔離級別。 yii\db\Transaction
$level integer 交易的目前巢狀層級。 yii\db\Transaction

公開方法

隱藏繼承的方法

方法 描述 定義於
__call() 呼叫未作為類別方法的具名方法。 yii\base\BaseObject
__construct() 建構子。 yii\base\BaseObject
__get() 傳回物件屬性的值。 yii\base\BaseObject
__isset() 檢查屬性是否已設定,即已定義且非 null。 yii\base\BaseObject
__set() 設定物件屬性的值。 yii\base\BaseObject
__unset() 將物件屬性設定為 null。 yii\base\BaseObject
begin() 開始一個交易。 yii\db\Transaction
canGetProperty() 傳回一個值,指示屬性是否可讀取。 yii\base\BaseObject
canSetProperty() 傳回一個值,指示屬性是否可設定。 yii\base\BaseObject
className() 傳回此類別的完整限定名稱。 yii\base\BaseObject
commit() 提交一個交易。 yii\db\Transaction
getIsActive() 傳回一個值,指示此交易是否為活動狀態。 yii\db\Transaction
getLevel() yii\db\Transaction
hasMethod() 傳回一個值,指示是否已定義方法。 yii\base\BaseObject
hasProperty() 傳回一個值,指示是否已定義屬性。 yii\base\BaseObject
init() 初始化物件。 yii\base\BaseObject
rollBack() 回滾一個交易。 yii\db\Transaction
setIsolationLevel() 設定此交易的交易隔離級別。 yii\db\Transaction

常數

隱藏繼承的常數

常數 描述 定義於
READ_COMMITTED 'READ COMMITTED' 一個常數,表示交易隔離級別 READ COMMITTED yii\db\Transaction
READ_UNCOMMITTED 'READ UNCOMMITTED' 一個常數,表示交易隔離級別 READ UNCOMMITTED yii\db\Transaction
REPEATABLE_READ 'REPEATABLE READ' 一個常數,表示交易隔離級別 REPEATABLE READ yii\db\Transaction
SERIALIZABLE 'SERIALIZABLE' 一個常數,表示交易隔離級別 SERIALIZABLE yii\db\Transaction

屬性詳細資訊

隱藏繼承的屬性

$db 公開屬性

此交易關聯的資料庫連線。

public yii\db\Connection $db null
$isActive public property

此交易是否為作用中。只有作用中的交易才能 commit()rollBack()

public boolean $isActive null
$isolationLevel public property

用於此交易的交易隔離級別。這可以是 READ_UNCOMMITTEDREAD_COMMITTEDREPEATABLE_READSERIALIZABLE 其中之一,也可以是包含 DBMS 特定語法的字串,用於 SET TRANSACTION ISOLATION LEVEL 之後。

public string $isolationLevel null
$level public property

交易的目前巢狀層級。

public integer $level null

方法詳情

隱藏繼承的方法

__call() public method

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

呼叫未作為類別方法的具名方法。

請勿直接調用此方法,因為它是 PHP 魔術方法,當調用未知方法時,它會被隱式調用。

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

方法名稱

$params array

方法參數

return mixed

方法返回值

throws yii\base\UnknownMethodException

當調用未知方法時

                public function __call($name, $params)
{
    throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}

            
__construct() public method

定義於: 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();
}

            
__get() public method

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

傳回物件屬性的值。

請勿直接調用此方法,因為它是 PHP 魔術方法,當執行 $value = $object->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)) {
        return $this->$getter();
    } elseif (method_exists($this, 'set' . $name)) {
        throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
    }
    throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}

            
__isset() public method

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

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

請勿直接調用此方法,因為它是 PHP 魔術方法,當執行 isset($object->property) 時,它會被隱式調用。

請注意,如果屬性未定義,將返回 false。

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

public boolean __isset ( $name )
$name string

屬性名稱或事件名稱

return boolean

具名屬性是否已設定(非 null)。

                public function __isset($name)
{
    $getter = 'get' . $name;
    if (method_exists($this, $getter)) {
        return $this->$getter() !== null;
    }
    return false;
}

            
__set() public method

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

設定物件屬性的值。

請勿直接調用此方法,因為它是 PHP 魔術方法,當執行 $object->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)) {
        $this->$setter($value);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
    } else {
        throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
    }
}

            
__unset() public method

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

將物件屬性設定為 null。

請勿直接調用此方法,因為它是 PHP 魔術方法,當執行 unset($object->property) 時,它會被隱式調用。

請注意,如果屬性未定義,此方法將不執行任何操作。如果屬性為唯讀,它將拋出例外。

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

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);
    } elseif (method_exists($this, 'get' . $name)) {
        throw new InvalidCallException('Unsetting read-only property: ' . get_class($this) . '::' . $name);
    }
}

            
begin() public method

開始一個交易。

public void begin ( $isolationLevel null )
$isolationLevel string|null

用於此交易的 隔離級別。這可以是 READ_UNCOMMITTEDREAD_COMMITTEDREPEATABLE_READSERIALIZABLE 其中之一,也可以是包含 DBMS 特定語法的字串,用於 SET TRANSACTION ISOLATION LEVEL 之後。如果未指定 (null),則不會顯式設定隔離級別,並將使用 DBMS 預設值。

注意:此設定不適用於 PostgreSQL,在 PostgreSQL 中,在交易之前設定隔離級別無效。在這種情況下,您必須在交易開始後調用 setIsolationLevel()

注意:某些 DBMS 僅允許為整個連線設定隔離級別,因此即使您未指定任何級別,後續交易也可能獲得相同的隔離級別。當使用此功能時,您可能需要為所有交易顯式設定隔離級別,以避免設定衝突。在撰寫本文時,受影響的 DBMS 是 MSSQL 和 SQLite。

從 2.0.16 版本開始,當開始巢狀交易且底層 DBMS 不支援儲存點時,此方法會拋出例外。

throws yii\base\InvalidConfigException

如果 $dbnull

throws yii\base\NotSupportedException

如果 DBMS 不支援巢狀交易

throws yii\db\Exception

如果資料庫連線失敗

                public function begin($isolationLevel = null)
{
    if ($this->db === null) {
        throw new InvalidConfigException('Transaction::db must be set.');
    }
    $this->db->open();
    if ($this->_level === 0) {
        if ($isolationLevel !== null) {
            $this->db->getSchema()->setTransactionIsolationLevel($isolationLevel);
        }
        Yii::debug('Begin transaction' . ($isolationLevel ? ' with isolation level ' . $isolationLevel : ''), __METHOD__);
        $this->db->trigger(Connection::EVENT_BEGIN_TRANSACTION);
        $this->db->pdo->beginTransaction();
        $this->_level = 1;
        return;
    }
    $schema = $this->db->getSchema();
    if ($schema->supportsSavepoint()) {
        Yii::debug('Set savepoint ' . $this->_level, __METHOD__);
        // make sure the transaction wasn't autocommitted
        if ($this->db->pdo->inTransaction()) {
            $schema->createSavepoint('LEVEL' . $this->_level);
        }
    } else {
        Yii::info('Transaction not started: nested transaction not supported', __METHOD__);
        throw new NotSupportedException('Transaction not started: nested transaction not supported.');
    }
    $this->_level++;
}

            
canGetProperty() public method

定義於: yii\base\BaseObject::canGetProperty()

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

如果符合以下任一條件,則屬性為可讀:

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

另請參閱 canSetProperty()

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

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否可讀

                public function canGetProperty($name, $checkVars = true)
{
    return method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name);
}

            
canSetProperty() public method

定義於: yii\base\BaseObject::canSetProperty()

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

如果符合以下任一條件,則屬性為可寫:

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

另請參閱 canGetProperty()

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

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否可寫

                public function canSetProperty($name, $checkVars = true)
{
    return method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name);
}

            
className() public static method
自 2.0.14 版本起已棄用。在 PHP >=5.5 上,請改用 ::class

定義於: yii\base\BaseObject::className()

傳回此類別的完整限定名稱。

public static string className ( )
return string

此類別的完整限定名稱。

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

            
commit() public method

提交一個交易。

public void commit ( )
throws yii\db\Exception

如果交易未作用中

                public function commit()
{
    if (!$this->getIsActive()) {
        throw new Exception('Failed to commit transaction: transaction was inactive.');
    }
    $this->_level--;
    if ($this->_level === 0) {
        Yii::debug('Commit transaction', __METHOD__);
        // make sure the transaction wasn't autocommitted
        if ($this->db->pdo->inTransaction()) {
            $this->db->pdo->commit();
        }
        $this->db->trigger(Connection::EVENT_COMMIT_TRANSACTION);
        return;
    }
    $schema = $this->db->getSchema();
    if ($schema->supportsSavepoint()) {
        Yii::debug('Release savepoint ' . $this->_level, __METHOD__);
        // make sure the transaction wasn't autocommitted
        if ($this->db->pdo->inTransaction()) {
            $schema->releaseSavepoint('LEVEL' . $this->_level);
        }
    } else {
        Yii::info('Transaction not committed: nested transaction not supported', __METHOD__);
    }
}

            
getIsActive() public method

傳回一個值,指示此交易是否為活動狀態。

public boolean getIsActive ( )
return boolean

此交易是否為作用中。只有作用中的交易才能 commit()rollBack()

                public function getIsActive()
{
    return $this->_level > 0 && $this->db && $this->db->isActive;
}

            
getLevel() public method (available since version 2.0.8)

public integer getLevel ( )
return integer

交易的目前巢狀層級。

                public function getLevel()
{
    return $this->_level;
}

            
hasMethod() public method

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

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

預設實作是對 php 函數 method_exists() 的調用。當您實作 php 魔術方法 __call() 時,您可以覆寫此方法。

public boolean hasMethod ( $name )
$name string

方法名稱

return boolean

方法是否已定義

                public function hasMethod($name)
{
    return method_exists($this, $name);
}

            
hasProperty() public method

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

傳回一個值,指示是否已定義屬性。

如果符合以下任一條件,則屬性已定義:

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

另請參閱

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

屬性名稱

$checkVars boolean

是否將成員變數視為屬性

return boolean

屬性是否已定義

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

            
init() public method

定義於: yii\base\BaseObject::init()

初始化物件。

在物件使用給定配置初始化後,此方法會在建構子的結尾被調用。

public void init ( )

                public function init()
{
}

            
rollBack() public method

回滾一個交易。

public void rollBack ( )

                public function rollBack()
{
    if (!$this->getIsActive()) {
        // do nothing if transaction is not active: this could be the transaction is committed
        // but the event handler to "commitTransaction" throw an exception
        return;
    }
    $this->_level--;
    if ($this->_level === 0) {
        Yii::debug('Roll back transaction', __METHOD__);
        // make sure the transaction wasn't autocommitted
        if ($this->db->pdo->inTransaction()) {
            $this->db->pdo->rollBack();
        }
        $this->db->trigger(Connection::EVENT_ROLLBACK_TRANSACTION);
        return;
    }
    $schema = $this->db->getSchema();
    if ($schema->supportsSavepoint()) {
        Yii::debug('Roll back to savepoint ' . $this->_level, __METHOD__);
        // make sure the transaction wasn't autocommitted
        if ($this->db->pdo->inTransaction()) {
            $schema->rollBackSavepoint('LEVEL' . $this->_level);
        }
    } else {
        Yii::info('Transaction not rolled back: nested transaction not supported', __METHOD__);
    }
}

            
setIsolationLevel() public method

設定此交易的交易隔離級別。

此方法可用於在交易已作用時設定隔離級別。但是,並非所有 DBMS 都支援此功能,因此您最好在調用 begin() 時直接指定隔離級別。

另請參閱 https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels

public void setIsolationLevel ( $level )
$level string

用於此交易的交易隔離級別。這可以是 READ_UNCOMMITTEDREAD_COMMITTEDREPEATABLE_READSERIALIZABLE 其中之一,也可以是包含 DBMS 特定語法的字串,用於 SET TRANSACTION ISOLATION LEVEL 之後。

throws yii\db\Exception

如果交易未作用中

                public function setIsolationLevel($level)
{
    if (!$this->getIsActive()) {
        throw new Exception('Failed to set isolation level: transaction was inactive.');
    }
    Yii::debug('Setting transaction isolation level to ' . $level, __METHOD__);
    $this->db->getSchema()->setTransactionIsolationLevel($level);
}