DEV Community

Hanane Kacemi
Hanane Kacemi

Posted on

Symfony & Doctrine: Part 3

Previously, I talked about how to create easily an Entity (ex:JOB) using a simple command line make:Entity and answering a few question(fields,type…).

This article will be about saving data to, fetching data from, the database.

Saving Data to DB :

To do so, we need to use a service provided by Doctrine, called EntityManagerInterface. The command symfony console debug:autowiring doctrine shows all doctrine services available.

Type-hint an argument $em to EntityManagerInterface, create an Object (ex $job), set all its properties then call persist and flush methods.

Persist object to Db

Calling persist() method tells Doctrine that we want to save the object, no query is executed yet. We call this method as many time as objects that we have, once we call flush() method, Doctrine execute the queries needed to insert to database.

We can check if data has been inserted with : symfony console doctrine:query:sql 'select * from job'

Data persisted to db

Fetching Data from DB :

Getting data(objects) from db is even easier, one way to do that is by using JobRepository $jobRepo as an argument in our method.

Fetch Data from DB

The repository class offers many helper methods to get our data from db like : findBy, findOneBy... We can also add custom methods to have complex queries, more about that in my next article.

Finally, I like to mention that Profiler provides a lot of tools to use when developing an app, for doctrine, it shows all queries executed :

Queries in Profiler

Thanks for reading and Happy new year :)

Top comments (0)