To save entry to db we can use:
$em->persist($entity);
$em->flush();
But how can we update existing entry without using $this->getEntityManager()->createQuery()
?
Can we?
I'm searching some kind of $em->update()
for existing entry in db.
Simple way to do, Fusselchen said right, just show an example
// get entity manager
$em = $this->getDoctrine()->getEntityManager();
// get from this entity manager our "entity" \ object in $item
// also we can get arrayCollection and then do all in foreach loop
$item = $em->getRepository('repoName')->findOneBy($filter);
// change "entity" / object values we want to edit
$item->setSome('someText')
//...
// call to flush that entity manager from which we create $item
$em->flush();
// after that in db column 'some' will have value 'someText'
// btw after call flush we can still use $item as 'selected object' in
// another $em calls and it will have actual (some = 'someText') values
No, it doesn't exist a function like $em->update()
.
You have to fetch object from DB and update it or, simply, write a custom query (with DQL) that update what you need
As you can see here
UPDATE MyProject\Model\User u SET u.password = 'new' WHERE u.id IN (1, 2, 3)
This is an example of DQL query for updating an entity named User
Last but not least important, this query have to be placed into aspecial "class" called repository that will contain all custom sql (dql). This is a good practice.
Learn more about repositories, here
no extra call for updating the database. The EntityManager keeps your model an Database in sync on flush()
public function updateAction($id)
{
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('AppBundle:Product')->find($id);
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$id
);
}
$product->setName('New product name!');
$em->flush();
return $this->redirectToRoute('homepage');
}
see http://symfony.com/doc/current/book/doctrine.html#updating-an-object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With