Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2, Doctrine, update db entry without queryBuilder

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.

like image 548
user1954544 Avatar asked Jan 30 '13 07:01

user1954544


3 Answers

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
like image 179
user1954544 Avatar answered Nov 04 '22 14:11

user1954544


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

like image 6
DonCallisto Avatar answered Nov 04 '22 13:11

DonCallisto


  1. Get the Entity from DB
  2. Change the values you want to modify
  3. flush the entitymanager

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

like image 3
Fusselchen Avatar answered Nov 04 '22 13:11

Fusselchen