如何使用实体管理器将数据存储到数据库中?

时间:2018-08-14 12:09:43

标签: php symfony controller doctrine entitymanager

这是我的变量$data的输出:

array(7) { [0]=> array(2) { ["name"]=> string(14) "form[username]" ["value"]=> string(1) "1" } [1]=> array(2) { ["name"]=> string(11) "form[email]" ["value"]=> string(7) "1@12.sw" } [2]=> array(2) { ["name"]=> string(15) "form[is_active]" ["value"]=> string(1) "1" } [3]=> array(2) { ["name"]=> string(26) "form[plainPassword][first]" ["value"]=> string(0) "" } [4]=> array(2) { ["name"]=> string(27) "form[plainPassword][second]" ["value"]=> string(0) "" } [5]=> array(2) { ["name"]=> string(8) "form[id]" ["value"]=> string(1) "9" } [6]=> array(2) { ["name"]=> string(12) "form[_token]" ["value"]=> string(43) "MdSCKxGkdFs2HPUSoM2vGidSRUmPgzZC3pZaW2wK2Rk" } } 

我现在想使用实体管理器更新数据库中的数据:

      $entityManager->persist($data);
      $entityManager = $data->getDoctrine()->getManager();
      $entityManager->flush();
      $response = new Response();
      $response->send();

但是我收到错误消息:

  

EntityManager#persist()期望参数1为实体对象,   给出NULL。

2 个答案:

答案 0 :(得分:2)

如果您的数据不包含一个新实体,则可以创建一个新实体。从表单值中获取正确的数据并将其放入set方法中。下面是一个小例子。

// Create new Entity
$entity = new EntityNameHere
$em = $this->getDoctrine()->getManager();

// Use setter function from that Entity
$entity->setName($data['name']);
$entity->setPassword($data['password']); 

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

答案 1 :(得分:1)

    if(is_object($data)) {
        $metadata = $em->getMetadataFactory()->getAllMetadata();
        $entities = [];
        foreach ($metadata as $entity){
            preg_match('/\w+$/',$entity->getName(), $o);
            $entities[] = $o[0];
        }
        if(in_array($data,$entities)){
            $em->persist($data);
            $em->flush();
        }
    } else {
        $query = null; //todo: $query
        $rsm = new ResultSetMapping(); //todo: fill $srm
        $em->createNativeQuery($query, $rsm)->execute();
    }