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 :)
Top comments (1)
I have simple question what if I want to retrieve URL for many paths stored in database how just the render will handle it using twig?
just at your explanation you mention that inside findby
for example I have avatar path stored in database like this ('image/avatar/1.jpb') then I have another one with two images but ('image/avatar/1.jpb'),(image/avatar/2.jpb') I just curious how I can add both in render output?