如何使用 Symfony 3.4 组件更新实体

How to update an Entity using Symfony 3.4 Components

为了回答我的问题,这里有一些我在发帖前看过的参考资料。

Doctrine Is not a valid entity or mapped super class

How to fix class is not a valid entity or mapped super class?

还有六个以上我没有列出。我收到的错误消息。

[18-Apr-2020 12:30:50 America/New_York] PHP Fatal error:  Uncaught Doctrine\ORM\Mapping\MappingException: Class "Doctrine\ORM\QueryBuilder" is not a valid entity or mapped super class. in C:\oerm_dev\www\dev\future5_2\vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\MappingException.php:346
Stack trace:
#0 C:\oerm_dev\www\dev\future5_2\vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\Driver\AnnotationDriver.php(93): Doctrine\ORM\Mapping\MappingException::classIsNotAValidEntityOrMappedSuperClass('Doctrine\ORM\Qu...')
#1 C:\oerm_dev\www\dev\future5_2\vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\ClassMetadataFactory.php(151): Doctrine\ORM\Mapping\Driver\AnnotationDriver->loadMetadataForClass('Doctrine\ORM\Qu...', Object(Doctrine\ORM\Mapping\ClassMetadata))
#2 C:\oerm_dev\www\dev\future5_2\vendor\doctrine\common\lib\Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory.php(332): Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata(Object(Doctrine\ORM\Mapping\ClassMetadata), NULL, false, Array)
#3 C:\oerm_dev\www\dev\future5_2\vendor\doctrine\orm\lib\Doctrine in C:\oerm_dev\www\dev\future5_2\vendor\doctrine\orm\lib\Doctrine\ORM\Mapping\MappingException.php on line 346

在对代码进行故障排除时我知道是这一行。

$this->_em->persist($qb);

我知道是这一行,因为如果我注释掉该行和它下面的行,代码 运行 就会通过而不会出现其他错误。但是,没有任何内容被保存。我已经看完了

https://www.doctrine-project.org/projects/doctrine-phpcr-odm/en/latest/reference/query-builder.html#the-querybuilder

虽然有很多从中获取数据的信息,但关于 UPDATE 的内容并不多。

https://symfony.com/doc/current/doctrine.html#updating-an-object

现在是代码

namespace OpenEMR\Repositories;

use Doctrine\ORM\EntityRepository;
use OpenEMR\Entities\FormEncounter;

class FormEncounterRepository extends EntityRepository
{
    /**
     * @param FormEncounter
     * @param $message
     * @return $response
     */

    public function update($message)
    {
        $response = false;
        $enc = $_SESSION['encounter'];
        try {
            $qb = $this->_em->getRepository($this->_entityName)->createQueryBuilder('fe');
            $qb->update(FormEncounter::class)
                ->set('fe.reason', 'text')
                ->where('fe.encounter', 'num')
                ->setParameter('text', $message)
                ->setParameter('num', $enc)
                ->getQuery();
            $this->_em->persist($qb);
            $this->_em->flush();
            $response = true;
        } catch (Exception $e) {
            return 'An Error occured during save: ' .$e->getMessage();
        }
        return $response;
    }
}

我的问题是为什么会抛出这个错误?我的代码与此非常接近,它使用插入命令并且可以正常工作。两者的主要区别在于 select 使用 Query::HYDRATE_ARRAY 函数。

好的,我明白了。这是一些我没有 运行 理解的信息。我做错了。

但是,https://symfony.com/doc/current/doctrine.html#updating-an-object 文档并没有告诉您他们坚持是因为。现在停止我的抱怨。

我回去改变了控制器代码的想法,据说坚持在那里而不是存储库。我添加了一个功能。这是我的控制器代码。

 /**
 * @param $message
 */
public function addAddendum(FormEncounter $message)
{
    //get current encounter
    $enc = $GLOBALS['encounter'];
    $reason = $this->repository;
    //get reason from database
    $getReason = $reason->findOneBy(['encounter' => $enc]);
    $this->updatedReason = $getReason->getReason() ."\r\n ADENDUM: \r\n". $message;
    self::updateReason($this->updateReason());

    return "Finished";

}

/**
 * @param \OpenEMR\Entities\FormEncounter $reason
 */
private function updateReason(FormEncounter $reason)
{
    try {
        //get current encounter
        $enc = $GLOBALS['encounter'];
        $aReason = $this->repository;
        $findReason = $aReason->findOneBy(['encounter' => $enc]);
        $this->save = $findReason->setReason($reason);
        $this->entityManager->persist($this->save);
        $this->entityManager->flush();
    } catch (Exception $e) {

    }
}

现在我有一个我无法弄清楚的新错误。

    [18-Apr-2020 20:33:17 America/New_York] PHP Fatal error:  Uncaught Error: Call to a member function persist() on null in C:\oerm_dev\www\dev\future5_2\src\Events\Addendum\AddendumEsign.php:71
Stack trace:
#0 C:\oerm_dev\www\dev\future5_2\src\Events\Addendum\AddendumEsign.php(54): OpenEMR\Events\Addendum\AddendumEsign->updateReason('Test Ribbon, no...')
#1 C:\oerm_dev\www\dev\future5_2\src\Events\Addendum\addendum_esign_helper.php(38): OpenEMR\Events\Addendum\AddendumEsign->addAddendum('This is a test ...')
#2 {main}
  thrown in C:\oerm_dev\www\dev\future5_2\src\Events\Addendum\AddendumEsign.php on line 71

所以,检查我的逻辑。 $findReason 调用数据库以返回我要更新的原因。找到我想更新的原因。 $this->save = $findReason->setReason($reason) 应该保存从 addAddendum() 方法传递的新原因对象。当我知道我传递了 $reason 对象时,错误告诉我第 71 行为空。

其中一些特定于我在其中工作的程序。错误消息只是帮助找出问题所在的指南。遵循错误消息,就我而言,这是找到正确解决方案的旅程。

此代码的目的是更新 table 中的字段并保存更新后的信息。

这些是 class。首先是控制器 class.

namespace OpenEMR\Events\Addendum;

use Doctrine\ORM\Mapping as ORM;
use OpenEMR\Common\Database\Connector;
use OpenEMR\Common\Logging\Logger;
use OpenEMR\Entities\FormEncounter;
use OpenEMR\Repositories\FormEncounterRepository;
use Symfony\Component\Config\Definition\Exception\Exception;

class AddendumEsign
{
    /**
     * @var
     */
    private $entityManager;
    private $repository;
    private $updatedReason;


    /**
     * @var string
     * @ORM\Column(type="string")
     */
    public function __construct()
    {
        $this->logger = new Logger(FormEncounterRepository::class);
        $database = Connector::Instance();
        $entityManager = $database->entityManager;
        $this->repository = $entityManager->getRepository(FormEncounter::class);
    }

    /**
     * the addAddendum is passed the addendum to be added to the reason 
     * that is currently in the form_encounter table. This method purpose is to edit
     * the currently stored reason
     */
    /**
     * @param $message
     * @return string
     */
    public function addAddendum($message)
    {
        //get current encounter
        $enc = $GLOBALS['encounter'];
        $reason = $this->repository;   //This is my database connector
        //get reason from database
        $getReason = $reason->findOneBy(['encounter' => $enc]);
        $this->updatedReason = $getReason->getReason() ."\r\n ADENDUM: \r\n". $message;
        self::setReason($this->updatedReason);

        return "Finished";

    }

    /**
     * The purpose of this block is to insert the new reason in to the object.
     * Then it is passed to the reposistory to save / update the reason.
     */
    /**
     * @param $reason
     */
    private function setReason($reason)
    {
        try {
            //get current encounter
            $enc = $GLOBALS['encounter'];
            $aReason = $this->repository;
            $findReason = $aReason->findOneBy(['encounter' => $enc]);
            //update the reason to the new reason for the addendum
            $findReason->setReason($reason);
            //call the reposistory to store the object and pass the object
            $save = $this->repository;
            $updatedReason = $save->update($findReason);
        } catch (Exception $e) {

        }
        return $updatedReason;
    }

}

现在是存储库 class。

namespace OpenEMR\Repositories;

use Doctrine\ORM\EntityRepository;
use OpenEMR\Entities\FormEncounter;
use Symfony\Component\Config\Definition\Exception\Exception;

class FormEncounterRepository extends EntityRepository
{
    /**
     * @param FormEncounter
     * @param $message
     * @return $response
     */

    public function update($message)
    {
        $response = false;
        try {
            //Since it is already an object ready for storing.
            //Doctrine can figure out from here to replace into database entry.
            //I learned that persist and flush only work in the repository and not in the controller. 
            $result = $this->_em->persist($message);
            $this->_em->flush();
            $response = true;
        } catch (Exception $e) {
            return 'An Error occured during save: ' .$e->getMessage();
        }
        return $response;
    }
}

希望这可以帮助寻找可能的答案的人。