Skip to content

Processing data

Apodemus Erectus edited this page Jun 10, 2020 · 16 revisions

This guide is about fetching data from your database and sending data to your database using Symfony.

The EntityManager

"The EntityManager is your friend. He can fetch data, send data, a really good guy overall." - Bryan Kho

This is the EntityManager, it can fetch data and send data from and to your database. You can access the Entity Manager from your controller.

$entityManager = $this->getDoctrine()->getManager();

You can also access the EntityManager via the EntityManagerInterface object, which you can add as an argument to your method inside your controller.

// don't forget the import
use Doctrine\ORM\EntityManagerInterface;

yourMethod(EntityManagerInterface $entityManager) {

}

Fetch Entity objects

You can use the getRepository() method of the EntityManager to find an object.

$product = $entityManager->getRepository(Product::class)->find($id);

besides the find() method on the Repository, you can also use findBy(), findAll() and findOneBy().

$product = $entityManager->getRepository(Product::class)->findOneBy(['id' => $id])

You can also access all your custom queries that you have made inside your Repository file.

$products = $entitymanager->getRepository(Product::class)->findAllGreaterThanPrice($minPrice);

Send Entity objects to the database

A new entity object you create must be persisted and then flushed in order to be sent to the database.

$product = new Product();

// prepare the new product for inserting it into the database
$entityManager->persist($product);

// execute the INSERT
$entityManager->flush();

If your object already exists, you don't have to call persist(), you can immediately flush().

$product = $entityManager->getRepository(Product::class)->find($id);

// execute the UPDATE
$entityManager->flush();

If you want to remove an existing object you have to call the remove() method.

$entityManager->remove($product);

Querying

There are different ways to make queries in symfony.

Inside your Repository

Inside your Controller

Clone this wiki locally