首页 > 解决方案 > 始终从数据库中获取实时数据的原则/清除正在破坏一切/棘轮聊天

问题描述

我正在使用 Ratchet PHP WebSockets 开发聊天。问题是我在那里使用 Doctrine 作为数据库层 - 并且脚本不会像正常的 Web 请求那样一直重新加载。

所以我决定$entityManager->clear()在每个连接上使用。(OnMessage)这一直有效,除了现在我想用通常的新用户保留新实体时。

用例:

onMessage

/** @var \Doctrine\Bundle\DoctrineBundle\Registry $doctrine */
$doctrine = $this->container->get('doctrine');
$doctrine->getManager()->clear();

$user = $this->container->get(UserRepository::class)->find(1);
// checks for is enabled etc. works because user is always fresh from the database so
// if I disable him while the script is running it will be detected

持久化从数据库加载新数据的实体。

$user = $this->container->get(UserRepository::class)->find($subscriber->Session->get('user_id'));
if ($user) {
    /** @var \Doctrine\Bundle\DoctrineBundle\Registry $doctrine */
    $doctrine = $this->container->get('doctrine');
    $doctrine->getManager()->refresh($user);

    echo 'BEFORE ERROR' . PHP_EOL;
    $chatMessageStatus = new ChatMessageStatus();
    $chatMessageStatus->setUser($user);
    $chatMessageStatus->setChatMessage($message);
    $this->entityManager->persist($chatMessageStatus);
    echo 'AFTER ERROR' . PHP_EOL;
}

错误:

A new entity was found through the relationship 'App\Entity\ChatMessageStatus#user' that was not configured to cascade persist operations for entity: patrick. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}).

我将 Symfony4 与 Doctrine ORM 2.5 一起使用。

提前感谢您的任何想法。

标签: phpdoctrine-ormentitymanagersymfony4

解决方案


推荐阅读