Skip to main content

Symfony Database

Doctrine

Doctrine is a PHP library that provides an Object Relational Mapper (ORM) for your database. It allows you to map your database tables to PHP objects and vice versa. It also provides a query builder and a schema builder.

The following commands will install Doctrine and its dependencies:

composer require symfony/orm-pack
composer require --dev symfony/maker-bundle

Configuring the database

Symfony uses the Doctrine ORM to interact with the database. The configuration of the database is done in the .env file.

# .env

# For MySQL
DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=5.7"

# For MariaDB
DATABASE_URL="mysql://db_user:db_password@127.0.0.1:3306/db_name?serverVersion=mariadb-10.5.8"

# For SQLite
DATABASE_URL="sqlite:///%kernel.project_dir%/var/app.db"

# For PostgreSQL
DATABASE_URL="postgresql://db_user:db_password@127.0.0.1:5432/db_name?serverVersion=11&charset=utf8"

# For Oracle
DATABASE_URL="oci8://db_user:db_password@127.0.0.1:1521/db_name"

Creating the database

To create the database, run the following command:

symfony console doctrine:database:create

Or in a shorter form:

symfony console d:d:c

Drop the database

To drop the database, run the following command:

symfony console doctrine:database:drop --force

Or in a shorter form:

symfony console d:d:d -f

Create a new entity

To create a new entity, run the following command:

symfony console make:entity

Create a new migration

To create a new migration, run the following command:

symfony console make:migration

Execute the migrations

To execute the migrations, run the following command:

symfony console doctrine:migrations:migrate

Or in a shorter form:

symfony console d:m:m

Create a new fixture

To create a new fixture, run the following command:

symfony console make:fixtures

Load the fixtures

To load the fixtures, run the following command:

symfony console doctrine:fixtures:load

Or in a shorter form:

symfony console d:f:l

Update the database schema

To update the database schema, run the following command:

symfony console doctrine:schema:update --force

Or in a shorter form:

symfony console d:s:u -f

List the available migrations and their status

To list the available migrations and their status, run the following command:

symfony console doctrine:migrations:list

Show the current migration

To show the current migration status, run the following command:

symfony console doctrine:migrations:current

Show the status of the migrations

To show the status of the migrations, run the following command:

symfony console doctrine:migrations:status

Check if the database schema is up to date

To check if the database schema is up to date, run the following command:

doctrine:migrations:up-to-date