首页 > 解决方案 > Doctrine find 方法将 id 渲染为字符串

问题描述

find当我使用类似的方法通过 id 获取对象时

$manager->getRepository(Country::class)->find(1);

给定的对象用字符串 Id 而不是 int 看起来很奇怪

Country {#41030 ▼
  +__isInitialized__: false
  -id: "1"
  -name: ""
}

但是当我取同一个国家时findOneBy

$manager->getRepository(Country::class)->findOneBy(['id' => 1]);

我得到了具有正确 id 类型的相同对象

Country {#41030 ▼
  +__isInitialized__: true
  -id: 1
  -name: "France"
}

如果我使用另一个实体尝试该find方法,则返回的对象具有正确类型的 id。

我试图找到这两个实体之间的差异但没有成功

当我在使用实体管理find器的侦听器中使用方法时,会导致奇怪的返回类型。LifecycleEventArg getEntityManager()

你有这样的案例吗?

编辑

Country实体定义

/**
 * @ORM\Table
 * @ORM\Entity
 * @DoctrineAssert\UniqueEntity("name")
 */
class Country
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(type="string", length=64, unique=true)
     * @Assert\NotBlank
     * @Assert\Length(max=64)
     */
    private $name = '';

    public function __toString(): string
    {
        return $this->id.' - '.$this->name;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getName(): string
    {
        return $this->name;
    }
}

标签: phpsymfonydoctrine-ormdoctrine

解决方案


推荐阅读