简体   繁体   English

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

[英]How to update an Entity using Symfony 3.4 Components

In defending my question, here are some of the references that I have looked at before posting.在为我的问题辩护时,这里有一些我在发布之前看过的参考资料。

Symfony Doctrine update query fail Symfony Doctrine 更新查询失败

Doctrine Is not a valid entity or mapped super class Doctrine 不是有效实体或映射的超级 class

How to fix class is not a valid entity or mapped super class? 如何修复 class 不是有效实体或映射的超级 class?

And there were more than a half dozen more that I am not listing.还有超过六个我没有列出。 The error message that I am getting this.我收到此错误消息。

[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

In troubleshooting the code I know that it is this line.在对代码进行故障排除时,我知道就是这一行。

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

I know it is this line because if I comment out that line and the line below it the code runs through with no additional errors.我知道是这一行,因为如果我注释掉该行及其下方的行,则代码将运行而不会出现其他错误。 However, nothing is saved.但是,什么都没有保存。 I have read over我读过

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

While there is a lot of information getting data from but there is not a lot written about UPDATE to.虽然有很多信息是从中获取数据的,但关于 UPDATE 的文章并不多。

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

Now here is the code现在这里是代码

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

My question is why is this error being thrown?我的问题是为什么会抛出这个错误? I have code very close to this the uses the insert command and it works.我的代码非常接近这个使用插入命令并且它可以工作。 The major difference in the two is that the select uses the Query::HYDRATE_ARRAY function.两者的主要区别在于 select 使用 Query::HYDRATE_ARRAY function。

Ok I get the point.好的,我明白了。 That was some information that I have not run across.那是一些我没有遇到过的信息。 I was doing it wrong.我做错了。

However, the https://symfony.com/doc/current/doctrine.html#updating-an-object documentation don't tell you that they are persisting because.但是, https://symfony.com/doc/current/doctrine.html#updating-an-object文档并没有告诉您它们会持续存在,因为。 Now to stop my whining.现在停止我的抱怨。

I went back in and changed the controller code thinking as was said to persist there and not the Repository.我回去并更改了 controller 代码,因为据说会持续存在而不是存储库。 I added a function.我添加了一个 function。 Here is my controller code.这是我的 controller 代码。

 /**
 * @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) {

    }
}

Now I have a new Error that I can't figure out.现在我有一个我无法弄清楚的新错误。

    [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

So, check my logic.所以,检查我的逻辑。 $findReason makes a call to the database to bring back the reason that I am looking to update. $findReason 调用数据库以恢复我要更新的原因。 On finding that reason that I want to update.找到我要更新的原因。 $this->save = $findReason->setReason($reason) should save the new reason object that was passed from the addAddendum() method. $this->save = $findReason->setReason($reason) 应该保存从 addAddendum() 方法传递的新原因 object。 The error is telling me that line 71 is null when I know I passed it $reason object.当我知道我通过了 $reason object 时,错误告诉我第 71 行是 null。

Some of this is specific to the program that I am working inside.其中一些特定于我正在内部工作的程序。 The error messages are only a guide to help figure out what is wrong.错误消息只是帮助找出问题所在的指南。 Following the error messages, it became a journey to get to the proper solution in my case.在收到错误消息之后,就我而言,它变成了找到正确解决方案的旅程。

The purpose of this code is to update a field in a table and save that updated information.此代码的目的是更新表中的字段并保存更新的信息。

These are the classes.这些是类。 First the controller class.首先是 controller 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;
    }

}

Now the repository class.现在存储库 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;
    }
}

Hope this helps someone looking for answers on what is possbile.希望这可以帮助某人寻找可能的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM