PrimaryReplicaTrait

Type
Trait
Namespace
craft\db
Implemented by
craft\db\Connection
Since
3.4.25

View source (opens new window)

# Public Methods

Method Description
getPrimary() Returns the currently active primary connection.
getPrimaryPdo() Returns the PDO instance for the currently active primary connection.
getReplica() Returns the currently active replica connection.
getReplicaPdo() Returns the PDO instance for the currently active replica connection.
usePrimary() Executes the provided callback by using the primary connection.

# getPrimary()

Returns the currently active primary connection.

If this method is called for the first time, it will try to open a primary connection.

View source (opens new window)

Returns

craft\db\Connection, null (opens new window) – The currently active primary connection. null is returned if no primary connection is available.

# getPrimaryPdo()

Returns the PDO instance for the currently active primary connection.

This method will open the primary DB connection and then return \craft\db\pdo.

View source (opens new window)

Returns

PDO (opens new window) – The PDO instance for the currently active primary connection.

# getReplica()

Returns the currently active replica connection.

If this method is called for the first time, it will try to open a replica connection when \craft\db\enableReplicas is true.

View source (opens new window)

Arguments

  • $fallbackToPrimary (boolean (opens new window)) – Whether to return the primary connection if no replica connections are available.

Returns

craft\db\Connection, null (opens new window) – The currently active replica connection. null is returned if no replica connections are available and $fallbackToPrimary is false.

# getReplicaPdo()

Returns the PDO instance for the currently active replica connection.

When \craft\db\enableReplicas is true, one of the replicas will be used for read queries, and its PDO instance will be returned by this method.

View source (opens new window)

Arguments

Returns

PDO (opens new window), null (opens new window) – The PDO instance for the currently active replica connection. null is returned if no replica connections are available and $fallbackToPrimary is false.

# usePrimary()

Executes the provided callback by using the primary connection.

This method is provided so that you can temporarily force using the primary connection to perform DB operations even if they are read queries. For example,

$result = $db->usePrimary(function ($db) {
    return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
});

View source (opens new window)

Arguments

  • $callback (callable (opens new window)) – A PHP callable to be executed by this method. Its signature is function (Connection $db). Its return value will be returned by this method.

Returns

mixed – The return value of the callback

Throws