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

How can I store my data into the database with the entity manager?

这是我的变量的输出 $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() expects parameter 1 to be an entity object, NULL given.

    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();
    }

如果您的数据不包含实体,您可以创建一个新实体。从表单值中获取正确的数据并将它们放入 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();