This content originally appeared on DEV Community and was authored by hanane kacemi
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.
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'
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.
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 :
Thanks for reading and Happy new year :)
This content originally appeared on DEV Community and was authored by hanane kacemi
hanane kacemi | Sciencx (2022-01-02T20:34:05+00:00) Symfony & Doctrine: Part 3. Retrieved from https://www.scien.cx/2022/01/02/symfony-doctrine-part-3/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.