繁体   English   中英

Symfony5 JMS 串行器 - model 具有计算属性,没有 ORM 注释

[英]Symfony5 JMS Serializer - model with calculated property without ORM annotation

我有这样的 model 属性:

/**
 * @ORM\Entity(repositoryClass=AssignmentRepository::class)
 */
class Assignment
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private ?int $id;
    
        /**
     * @ORM\Column(type="float", nullable=true)
     */
    private ?float $sale;

    /**
     * @ORM\Column(type="float", nullable=true)
     */
    private ?float $cost;

    /**
     * @JMS\Type("integer")
     */
    private ?float $marge = null;

    .... 

    
    public function getSale(): ?float
    {
        return $this->sale;
    }

    public function setSale(?float $sale): self
    {
        $this->sale = $sale;

        return $this;
    }

    public function getCost(): ?float
    {
        return $this->cost;
    }

    public function setCost(?float $cost): self
    {
        $this->cost = $cost;

        return $this;
    }
    
    public function getMarge(): ?float
    {
        return $this->getSale() - $this->getCost();
    }

如您所见, $this->sale 和 $this->cost 是保存在我的数据库中的 ORM 属性。 $this->marge 是一个非映射属性,由费率和成本之间的差异决定。

但是当我用 controller 得到这个并用 JMS 序列化器序列化它时, $this->marge 属性不存在。 关键的“marge”不存在。

像这样使用序列化程序获取它:

$result = $this->assignmentRepository->findAll();

return new JsonResponse(
    $serializer->serialize($result, JsonEncoder::FORMAT),
    Response::HTTP_OK,
    [],
    true
);

当我这样调试时:

dump($this->assignmentRepository->find(1));

我得到了 object 属性“marge”= null(虽然售价为 500,成本为 400 - 预计为 100)。 当我尝试明确时:

dump($this->assignmentRepository->find(1)->getMarge());

我得到的值为“100”。 为什么? 我需要“marge”的值而不像这样明确调用:

$this->assignmentRepository->find(1);

问题:

我怎样才能获得完整的 object 信息以及所有属性,如“销售”、“成本”和“marge”的有效计算值(非映射 doctrine 实体以及销售和成本之间的差异)?

你的属性$marge没有设置,你永远不会做$this->marge = something

请查看有关VirtualProperty的文档部分,注释应位于方法getMarge上方,因为您的属性没有价值

移除marge属性并为getMarge方法添加注解

/**
 * @JMS\VirtualProperty()
 */
public function getMarge(): float
{
    return $this->getSale() - $this->getCost();
}

另外,如果您将结果包装成round()会更好,因为您使用 float 类型

暂无
暂无

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

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