这是我的实体Cats
的摘录:
....
/**
* @ORM\ManyToOne(targetEntity="Dogs")
* @ORM\JoinColumn(name="type", referencedColumnName="id")
*/
private $type;
public function getType(): ?Dogs
{
return $this->type;
}
public function setType(?Dogs $type): self
{
$this->type = $type;
return $this;
}
实体Dogs
的这个:
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=25)
*/
private $name;
public function getId()
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
现在type
设置为“ 2”:
2 => Cats {#6214 ▼
-id: 3
-name: "password"
-type: Dogs {#6211 ▼
+__isInitialized__: true
-id: 2
-name: "hidden"
-label: "hidden"
…2
…2}
}
我想将其更新为“ 3”:
$entity->setType(2);
$em->flush();
但是我收到错误消息:
传递给App \ Entity \ Cats :: setType()的参数1必须是一个实例 App \ Entity \ Dogs或null,给出字符串,在 /Users/work/project/src/Controller/PagesController.php在第242行
如何创建实体实例?
答案 0 :(得分:3)
实际上,由于您获得了相关实体的ID,因此不需要从数据库中完全加载该实体,您只需将引用传递给该实体。这样更快,并且不会在代码中增加不必要的开销:
$dogId = 3;
$dog = $em->getReference(Dogs::class, $dogId);
$entity->setType($dog);
$em->flush();
答案 1 :(得分:1)
您不能将类型设置为狗实体的ID,而是直接设置为该实体。您需要执行以下操作:
$dog = $em->getRepository(Dog::class)->findOneById(2);
$entity->setType($dog);
$em->flush();