use*_*544 10 database doctrine symfony
要保存对db的输入,我们可以使用:
$em->persist($entity);
$em->flush();
Run Code Online (Sandbox Code Playgroud)
但是我们怎样才能更新现有的条目而不使用$this->getEntityManager()->createQuery()?
我们可以吗?
我正在搜索$em->update()db中的某些现有条目.
use*_*544 13
简单的方法,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
Run Code Online (Sandbox Code Playgroud)
不,它不存在像这样的功能$em->update().
您必须从数据库中获取对象并更新它,或者简单地编写一个自定义查询(使用DQL)来更新您需要的内容
正如你在这里看到的那样
UPDATE MyProject\Model\User u SET u.password = 'new' WHERE u.id IN (1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
这是用于更新名为User的实体的DQL查询示例
最后但并非最不重要的是,此查询必须放入称为存储库的特殊"类"中,该存储库将包含所有自定义sql(dql).这是一个很好的做法.
在此处了解有关存储库的更多信息