【问题标题】:How to update an Entity using Symfony 3.4 Components如何使用 Symfony 3.4 组件更新实体
【发布时间】:2020-04-18 17:05:19
【问题描述】:

在为我的问题辩护时,以下是我在发布之前查看的一些参考资料。

Symfony Doctrine update query fail

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 行为空。

【问题讨论】:

  • 为什么要保留查询生成器?持久用于实体
  • 两件事:1.您试图持久化查询构建器对象而不是实体。 2.一个存储库类,如果用于组织您的查询,而不是用于更新实体。这可以在控制器或服务中完成。
  • @DirkJ.Faber 我搬回了控制器,但现在我有一个空错误。现在会是什么?
  • 你的 symfony 版本是多少?
  • 3.4 是当前程序中的版本。 @ArnoldRichmon 我们在我们的程序中使用 Symfony 组件。

标签: php symfony doctrine-orm


【解决方案1】:

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

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

这些是类。首先是控制器类。

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

}

现在是存储库类。

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

希望这有助于有人寻找可能的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多