如何使用 Dcotrine 刷新一个实体而不刷新另一个实体


How to flush one entity without flushing another using Dcotrine?

如何只刷新一个实体而不刷新其他实体?

例如:我有 2 个对象 BStatus 和 B。它们通过一对一关系相关。我想在 B 上做一些工作而不将其保存到数据库,但将工作状态保存在 BStatus 上,以便另一个进程可以读取它。

class B {
    /**
     * @var int
     * @ORM'Column(type="integer")
     */
    public $i = 0;
    /**
     * @var BStatus
     * @ORM'OneToOne(targetEntity="BStatus", inversedBy="b")
     */
    public $status;
    /**
     * B constructor.
     */
    public function __construct() {
        $this->status = new BStatus($this);
    }
    public function count() {
        return $this->i++;
    }
}
class BStatus {
    /**
     * @var float
     * @ORM'Column(type="float")
     */
    public $progress = 0;
    // <UPDATED>
    /**
     * @var B
     * @ORM'OneToOne(targetEntity="B", mappedBy="status")
     */
    public $progress = 0;
    // </UPDATED>
    /**
     * BStatus constructor.
     * @param B $b
     */
    public function __construct(B $b)
    {
        $this->b = $b;
    }
}

$b = // Load from DB
$max = 100;
for ($i = 0; $i < $max; $i++) {
    $num = $b->count();
    $b->getStatus()->setProgress(($num + 1) / $max);
    // Here I want to save the status
}
// Here I want to save $b

更新BStatus有指向B的指针。

更新 2

已尝试分离B,冲洗并合并B。

for ($i = 0; $i < $max; $i++) {
    $num = $b->count();
    $status = $b->getStatus();
    $status->setProgress(($num + 1) / $max);
    $em->detach($b);
    $em->flush();
    $em->merge($b);
}

得到执行:

 'Doctrine'ORM'ORMInvalidArgumentException' with message 'A new entity was found through the relationship BStatus#b' that was not configured to cascade persist operations for entity: local. 
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"}).'
$em->flush($b);

将仅刷新指定的实体。 看起来在线文档没有显示此功能,但实际代码的峰值表明至少从 Doctrine 2.4 开始就是这些。

您可以将对象与工作单元分离

$em->detach($instanceOfB)