Skip to content

DbConfig

Type
Class
Namespace
craft\config
Inherits
craft\config\DbConfig » craft\config\BaseConfig » craft\base\Model » yii\base\Model » yii\base\Component » yii\base\BaseObject
Implements
ArrayAccess, IteratorAggregate, craft\base\ModelInterface, yii\base\Arrayable, yii\base\Configurable, yii\base\StaticInstanceInterface
Uses traits
craft\base\ClonefixTrait, yii\base\ArrayableTrait, yii\base\StaticInstanceTrait
Since
3.0.0

DB config class

View source

Public Properties

PropertyDescription
activeValidatorsyii\validators\Validator – The validators applicable to the current scenario.
attributesarray – An array of key-value pairs of PDO attributes to pass into the PDO constructor.
behaviorsyii\base\Behavior – List of behaviors attached to this component.
charsetstring – The charset to use when creating tables.
collationstring, null – The collation to use when creating tables.
databasestring, null – The name of the database to select.
driverstring, null – The database driver to use.
dsnstring, null – The Data Source Name (“DSN”) that tells Craft how to connect to the database.
errorsarray – Errors for all attributes or the specified attribute.
firstErrorsarray – The first errors.
iteratorArrayIterator – An iterator for traversing the items in the list.
passwordstring – The database password to connect with.
portinteger, null – The database server port.
scenariostring – The scenario that this model is in.
schemastring, null – The schema that Postgres is configured to use by default (PostgreSQL only).
serverstring, null – The database server name or IP address.
setSchemaOnConnectboolean – Whether the schema() should be explicitly used for database queries (PostgreSQL only).
tablePrefixstring, null – If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), you can set a table prefix here to avoid per-install table naming conflicts.
unixSocketstring, null – MySQL only.
urlstring, null – The database connection URL, if one was provided by your hosting environment.
useUnbufferedConnectionsboolean – Whether batched queries should be executed on a separate, unbuffered database connection.
userstring – The database username to connect with.
validatorsArrayObject, yii\validators\Validator – All the validators declared in the model.

attributes

Type
array
Default value
[]

An array of key-value pairs of PDO attributes to pass into the PDO constructor.

For example, when using the MySQL PDO driver, if you wanted to enable a SSL database connection (assuming SSL is enabled in MySQL and 'user' can connect via SSL, you’d set these:

php
->attributes([
    PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem',
    PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem',
    PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem',
])

View source

charset

Type
string
Default value
'utf8'

The charset to use when creating tables.

TIP

You can change the character set and collation across all existing database tables using this terminal command:

bash
php craft db/convert-charset

::: code

php
->charset('utf8mb4')
shell
CRAFT_DB_CHARSET=utf8mb4

:::

View source

collation

Type
string, null
Default value
null
Since
3.6.4

The collation to use when creating tables.

This is only used by MySQL. If null, the charset’s default collation will be used.

CharsetDefault collation
utf8utf8_general_ci
utf8mb4utf8mb4_0900_ai_ci

TIP

You can change the character set and collation across all existing database tables using this terminal command:

bash
php craft db/convert-charset

::: code

php
->collation('utf8mb4_0900_ai_ci')
shell
CRAFT_DB_COLLATION=utf8mb4_0900_ai_ci

:::

View source

database

Type
string, null
Default value
null

The name of the database to select.

::: code

php
->database('mydatabase')
shell
CRAFT_DB_DATABASE=mydatabase

:::

View source

driver

Type
string, null
Default value
null

The database driver to use. Either mysql for MySQL or pgsql for PostgreSQL.

::: code

php
->driver('mysql')
shell
CRAFT_DB_DRIVER=mysql

:::

View source

dsn

Type
string, null
Default value
null

The Data Source Name (“DSN”) that tells Craft how to connect to the database.

DSNs should begin with a driver prefix (mysql: or pgsql:), followed by driver-specific parameters. For example, mysql:host=127.0.0.1;port=3306;dbname=acme_corp.

::: code

php
->dsn('mysql:host=127.0.0.1;port=3306;dbname=acme_corp')
shell
CRAFT_DB_DSN=mysql:host=127.0.0.1;port=3306;dbname=acme_corp

:::

View source

password

Type
string
Default value
''

The database password to connect with.

::: code

php
->password('super-secret')
shell
CRAFT_DB_PASSWORD=super-secret

:::

View source

port

Type
integer, null
Default value
null

The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL.

::: code

php
->port(3306)
shell
CRAFT_DB_PORT=3306

:::

View source

schema

Type
string, null
Default value
'public'

The schema that Postgres is configured to use by default (PostgreSQL only).

TIP

To force Craft to use the specified schema regardless of PostgreSQL’s search_path setting, you must enable the setSchemaOnConnect() setting.

::: code

php
->schema('myschema,public')
shell
CRAFT_DB_SCHEMA=myschema,public

:::

See also https://www.postgresql.org/docs/8.2/static/ddl-schemas.html

View source

server

Type
string, null
Default value
null

The database server name or IP address. Usually localhost or 127.0.0.1.

::: code

php
->server('localhost')
shell
CRAFT_DB_SERVER=localhost

:::

View source

setSchemaOnConnect

Type
boolean
Default value
false
Since
3.7.27

Whether the schema() should be explicitly used for database queries (PostgreSQL only).

WARNING

This will cause an extra SET search_path SQL query to be executed per database connection. Ideally, PostgreSQL’s search_path setting should be configured to prioritize the desired schema.

::: code

php
->setSchemaOnConnect(true)
shell
CRAFT_DB_SET_SCHEMA_ON_CONNECT=true

:::

View source

tablePrefix

Type
string, null
Default value
null

If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase.

::: code

php
->tablePrefix('craft_')
shell
CRAFT_DB_TABLE_PREFIX=craft_

:::

View source

unixSocket

Type
string, null
Default value
null

MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of the server and port. If this is specified, then server and port settings are ignored.

::: code

php
->unixSocket('/Applications/MAMP/tmp/mysql/mysql.sock')
shell
CRAFT_DB_UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

:::

View source

url

Type
string, null
Default value
null

The database connection URL, if one was provided by your hosting environment.

If this is set, the values for driver(), user(), database(), server(), port(), and database() will be extracted from it.

::: code

php
->url('jdbc:mysql://database.foo:3306/mydb')
shell
CRAFT_DB_URL=jdbc:mysql://database.foo:3306/mydb

:::

View source

useUnbufferedConnections

Type
boolean
Default value
false
Since
3.7.0

Whether batched queries should be executed on a separate, unbuffered database connection.

This setting only applies to MySQL. It can be enabled when working with high volume content, to prevent PHP from running out of memory when querying too much data at once. (See https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#batch-query-mysql for an explanation of MySQL’s batch query limitations.)

For more on Craft batch queries, see https://craftcms.com/knowledge-base/query-batching-batch-each.

::: code

php
->useUnbufferedConnections(true)
shell
CRAFT_DB_USE_UNBUFFERED_CONNECTIONS=true

:::

View source

user

Type
string
Default value
'root'

The database username to connect with.

::: code

php
->user('db')
shell
CRAFT_DB_USER=db

:::

View source

Protected Properties

PropertyDescription
filenamestring, null – The config filename
renamedSettingsarray – Settings that have been renamed

filename

Type
string, null
Default value
\craft\services\Config::CATEGORY_DB

The config filename

View source

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__clone()This method is called after the object is created by cloning an existing one.
__construct()
__get()Returns the value of a component property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets the value of a component property.
__unset()Sets a component property to be null.
activeAttributes()Returns the attribute names that are subject to validation in the current scenario.
addError()Adds a new error to the specified attribute.
addErrors()Adds a list of errors.
addModelErrors()Adds errors from another model, with a given attribute name prefix.
afterValidate()This method is invoked after validation ends.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
attributeHints()Returns the attribute hints.
attributeLabels()Returns the attribute labels.
attributes()Returns the list of attribute names.
beforeValidate()This method is invoked before validation starts.
behaviors()Returns a list of behaviors that this component should behave as.
canGetProperty()Returns a value indicating whether a property can be read.
canSetProperty()Returns a value indicating whether a property can be set.
charset()The charset to use when creating tables.
className()Returns the fully qualified name of this class.
clearErrors()Removes errors for all attributes or a single attribute.
collation()The collation to use when creating tables.
create()Factory method for creating new config objects.
createValidators()Creates validator objects based on the validation rules specified in rules().
database()The name of the database to select.
datetimeAttributes()Returns the names of any attributes that should hold DateTime values.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
driver()The database driver to use. Either mysql for MySQL or pgsql for PostgreSQL.
dsn()The Data Source Name (“DSN”) that tells Craft how to connect to the database.
ensureBehaviors()Makes sure that the behaviors declared in behaviors() are attached to this component.
extraFields()Returns the list of fields that can be expanded further and returned by toArray().
fields()Returns the list of fields that should be returned by default by toArray() when no specific fields are specified.
formName()Returns the form name that this model class should use.
generateAttributeLabel()Generates a user friendly attribute label based on the give attribute name.
getActiveValidators()Returns the validators applicable to the current scenario.
getAttributeHint()Returns the text hint for the specified attribute.
getAttributeLabel()Returns the text label for the specified attribute.
getAttributes()Returns attribute values.
getBehavior()Returns the named behavior object.
getBehaviors()Returns all behaviors attached to this component.
getErrorSummary()Returns the errors for all attributes as a one-dimensional array.
getErrors()Returns the errors for all attributes or a single attribute.
getFirstError()Returns the first error of the specified attribute.
getFirstErrors()Returns the first error of every attribute in the model.
getIterator()Returns an iterator for traversing the attributes in the model.
getScenario()Returns the scenario that this model is used in.
getValidators()Returns all the validators declared in rules().
hasErrors()Returns a value indicating whether there is any validation error.
hasEventHandlers()Returns a value indicating whether there is any handler attached to the named event.
hasMethod()Returns a value indicating whether a method is defined.
hasProperty()Returns a value indicating whether a property is defined for this component.
init()Initializes the object.
instance()Returns static class instance, which can be used to obtain meta information.
isAttributeActive()Returns a value indicating whether the attribute is active in the current scenario.
isAttributeRequired()Returns a value indicating whether the attribute is required.
isAttributeSafe()Returns a value indicating whether the attribute is safe for massive assignments.
load()Populates the model with input data.
loadMultiple()Populates a set of models with the data from end user.
off()Detaches an existing event handler from this component.
offsetExists()Returns whether there is an element at the specified offset.
offsetGet()Returns the element at the specified offset.
offsetSet()Sets the element at the specified offset.
offsetUnset()Sets the element value at the specified offset to null.
on()Attaches an event handler to an event.
onUnsafeAttribute()This method is invoked when an unsafe attribute is being massively assigned.
password()The database password to connect with.
pdoAttributes()An array of key-value pairs of PDO attributes to pass into the PDO constructor.
port()The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL.
rules()Returns the validation rules for attributes.
safeAttributes()Returns the attribute names that are safe to be massively assigned in the current scenario.
scenarios()Returns a list of scenarios and the corresponding active attributes.
schema()The schema that Postgres is configured to use by default (PostgreSQL only).
server()The database server name or IP address. Usually localhost or 127.0.0.1.
setAttributes()Sets the attribute values in a massive way.
setScenario()Sets the scenario for the model.
setSchemaOnConnect()Whether the schema() should be explicitly used for database queries (PostgreSQL only).
tablePrefix()If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase.
toArray()Converts the model into an array.
trigger()Triggers an event.
unixSocket()MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of the server and port. If this is specified, then server and port settings are ignored.
url()The database connection URL, if one was provided by your hosting environment.
useUnbufferedConnections()Whether batched queries should be executed on a separate, unbuffered database connection.
user()The database username to connect with.
validate()Performs the data validation.
validateMultiple()Validates multiple models.

charset()

Since
4.2.0

The charset to use when creating tables.

TIP

You can change the character set and collation across all existing database tables using this terminal command:

bash
php craft db/convert-charset
php
->charset('utf8mb4')

View source

Arguments

Returns

self

collation()

Since
4.2.0

The collation to use when creating tables.

This is only used by MySQL. If null, the charset’s default collation will be used.

CharsetDefault collation
utf8utf8_general_ci
utf8mb4utf8mb4_0900_ai_ci

TIP

You can change the character set and collation across all existing database tables using this terminal command:

bash
php craft db/convert-charset
php
->collation('utf8mb4_0900_ai_ci')

View source

Arguments

Returns

self

database()

Since
4.2.0

The name of the database to select.

php
->database('mydatabase')

View source

Arguments

Returns

self

Throws

driver()

Since
4.2.0

The database driver to use. Either mysql for MySQL or pgsql for PostgreSQL.

php
->driver('mysql')

View source

Arguments

Returns

self

Throws

dsn()

Since
4.2.0

The Data Source Name (“DSN”) that tells Craft how to connect to the database.

DSNs should begin with a driver prefix (mysql: or pgsql:), followed by driver-specific parameters. For example, mysql:host=127.0.0.1;port=3306;dbname=acme_corp.

php
->dsn('mysql:host=127.0.0.1;port=3306;dbname=acme_corp')

View source

Arguments

Returns

self

init()

Initializes the object.

This method is invoked at the end of the constructor after the object is initialized with the given configuration.

View source

Throws

password()

Since
4.2.0

The database password to connect with.

php
->password('super-secret')

View source

Arguments

Returns

self

pdoAttributes()

Since
4.2.0

An array of key-value pairs of PDO attributes to pass into the PDO constructor.

For example, when using the MySQL PDO driver, if you wanted to enable a SSL database connection (assuming SSL is enabled in MySQL and 'user' can connect via SSL, you’d set these:

php
->pdoAttributes([
    PDO::MYSQL_ATTR_SSL_KEY => '/path/to/my/client-key.pem',
    PDO::MYSQL_ATTR_SSL_CERT => '/path/to/my/client-cert.pem',
    PDO::MYSQL_ATTR_SSL_CA => '/path/to/my/ca-cert.pem',
])

View source

Arguments

Returns

self

port()

Since
4.2.0

The database server port. Defaults to 3306 for MySQL and 5432 for PostgreSQL.

php
->port(3306)

View source

Arguments

Returns

self

Throws

schema()

Since
4.2.0

The schema that Postgres is configured to use by default (PostgreSQL only).

TIP

To force Craft to use the specified schema regardless of PostgreSQL’s search_path setting, you must enable the setSchemaOnConnect() setting.

php
->schema('myschema,public')

See also https://www.postgresql.org/docs/8.2/static/ddl-schemas.htmlView source

Arguments

Returns

self

server()

Since
4.2.0

The database server name or IP address. Usually localhost or 127.0.0.1.

php
->server('localhost')

View source

Arguments

Returns

self

Throws

setSchemaOnConnect()

Since
4.2.0

Whether the schema() should be explicitly used for database queries (PostgreSQL only).

WARNING

This will cause an extra SET search_path SQL query to be executed per database connection. Ideally, PostgreSQL’s search_path setting should be configured to prioritize the desired schema.

php
->setSchemaOnConnect()

View source

Arguments

Returns

self

tablePrefix()

Since
4.2.0

If you’re sharing Craft installs in a single database (MySQL) or a single database and using a shared schema (PostgreSQL), you can set a table prefix here to avoid per-install table naming conflicts. This can be no more than 5 characters, and must be all lowercase.

php
->tablePrefix('craft_')

View source

Arguments

Returns

self

Throws

unixSocket()

Since
4.2.0

MySQL only. If this is set, the CLI connection string (used for yiic) will connect to the Unix socket instead of the server and port. If this is specified, then server and port settings are ignored.

php
->unixSocket('/Applications/MAMP/tmp/mysql/mysql.sock')

View source

Arguments

Returns

self

Throws

url()

Since
4.2.0

The database connection URL, if one was provided by your hosting environment.

If this is set, the values for driver(), user(), database(), server(), port(), and database() will be extracted from it.

php
->url('jdbc:mysql://database.foo:3306/mydb')

View source

Arguments

Returns

self

useUnbufferedConnections()

Since
4.2.0

Whether batched queries should be executed on a separate, unbuffered database connection.

This setting only applies to MySQL. It can be enabled when working with high volume content, to prevent PHP from running out of memory when querying too much data at once. (See https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#batch-query-mysql for an explanation of MySQL’s batch query limitations.)

For more on Craft batch queries, see https://craftcms.com/knowledge-base/query-batching-batch-each.

php
->useUnbufferedConnections()

View source

Arguments

Returns

self

user()

Since
4.2.0

The database username to connect with.

php
->user('db')

View source

Arguments

Returns

self

Protected Methods

MethodDescription
defineBehaviors()Returns the behaviors to attach to this class.
defineRules()Returns the validation rules for attributes.
extractFieldsFor()Extract nested fields from a fields collection for a given root field Nested fields are separated with dots (.). e.g: "item.id" The previous example would extract "id".
extractRootFields()Extracts the root field names from nested fields.
resolveFields()Determines which fields can be returned by toArray().

Constants

ConstantDescription
DRIVER_MYSQL
DRIVER_PGSQL
SCENARIO_DEFAULTThe name of the default scenario.