Symfony2、Doctrine:不使用 queryBuilder 更新数据库条目

12

我们可以使用以下方法将条目保存到数据库中:

$em->persist($entity);
$em->flush();

如何在不使用$this->getEntityManager()->createQuery()的情况下更新现有条目?

我们能吗?

我正在寻找一种可以更新数据库中现有条目的$em->update()方式。

3个回答

14

做法很简单,Fusselchen 说得对,只需要举个例子就行了

// 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

6
不,不存在像$em->update()这样的函数。您需要从数据库中获取对象并更新它,或者简单地编写自定义查询(使用DQL)来更新所需内容。
正如您可以在这里看到的那样。
UPDATE MyProject\Model\User u SET u.password = 'new' WHERE u.id IN (1, 2, 3)

这是一个用于更新名为“User”的实体的DQL查询示例。

最后但同样重要的是,此查询必须放置在一个特殊的“类”中,称为存储库,该存储库将包含所有自定义SQL(DQL)。这是一个好习惯。

了解有关存储库的更多信息,请在此处查看。


谢谢您的回答,也很有用,但上面的人先回答了。再次感谢。 - user1954544
@user1954544 他不是第一个。我回答是29分钟之前,而他是18分钟之前,所以我的是第一个。但没关系... - DonCallisto
@user1954544:附注:最佳答案必须被接受,而不是“最快的”答案。 - DonCallisto
不,像$em->update()这样的函数不存在。这是错误的,dql中的合并操作确切地用于更新现在与管理器分离的模型。它基本上会为您执行选择部分,因此合并是更新的最近等效项。 - AlTak
@AlTal 我猜你既没有理解问题,也没有理解答案。 - DonCallisto

3
  1. 从数据库获取实体
  2. 更改您想要修改的值
  3. 刷新实体管理器

无需额外调用即可更新数据库。EntityManager 会在 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');
}

请查看http://symfony.com/doc/current/book/doctrine.html#updating-an-object以了解如何更新一个对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接