Login to bookmark this video
Buy Access to Course
02.

Database Config and Automatic Table Creation

Share this awesome video!

|

We described the genus table to Doctrine via annotations, but this table doesn't exist yet. No worries - Doctrine can create it for us!

And actually, we don't even have a database yet. Doctrine can also handle this. Head to the terminal use the console to run:

./bin/console doctrine:database:create

But wait! Can Doctrine do this yet? We haven't told it anything about the database: not the name we want, the user or the password.

Configuring the Database

Where do we do that? The same place that everything, meaning all services are configured: app/config/config.yml. Scroll down to the doctrine key:

72 lines | app/config/config.yml
// ... lines 1 - 43
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
# path: "%database_path%"
// ... lines 60 - 72

Ah, this is what tells Doctrine all about your database connection.

But, the information is not hardcoded here - these are references to parameters that are defined in parameters.yml:

15 lines | app/config/parameters.yml.dist
// ... lines 1 - 3
parameters:
database_host: 127.0.0.1
database_port: ~
database_name: symfony
database_user: root
database_password: ~
# You should uncomment this if you want use pdo_sqlite
# database_path: "%kernel.root_dir%/data.db3"
// ... lines 12 - 15

Update the database_name to aqua_note and on my super-secure local machine, the database user is root with no password.

Go Deeper!

Find out more about these parameters in our Symfony Fundamentals Series.

Back to the terminal! Now hit enter on the command:

./bin/console doctrine:database:create

Database created. To create the table, run:

./bin/console doctrine:schema:update --dump-sql

This looks great - CREATE TABLE genus with the two columns. But this didn't execute the query yet - the --dump-sql option is used to preview the query if you're curious. Replace it with --force.

./bin/console doctrine:schema:update --force

So hey guys, this is really cool - we can be totally lazy and let Doctrine do all the heavy database-lifting for us. This doctrine:schema:update command is actually more powerful than it looks - it's going to "wow" us in a few minutes.

But first, let's learn how to insert data into the new table.