gpt4 book ai didi

php - Doctrine:仅使用 id 来设置相关实体

转载 作者:行者123 更新时间:2023-12-05 01:13:24 26 4
gpt4 key购买 nike

我有两个实体:产品和类别。一个产品可以属于一个类别,因此两个实体之间存在 OneToMany 关系:

/**
* @ORM\Entity()
*/
class Category
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;

/**
* @ORM\Column(type="string", length=255)
*/
private $name;

/**
* @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="category")
*/
private $products;

public function __construct()
{
$this->products = new ArrayCollection();
}

public function getProducts(): Collection
{
return $this->products;
}

public function addProduct(Product $product): self
{
if (!$this->products->contains($product)) {
$this->products[] = $product;
$product->setCategory($this);
}

return $this;
}

public function removeProduct(Product $product): self
{
if ($this->products->contains($product)) {
$this->products->removeElement($product);
$product->setCategory(null);
}
return $this;
}

// Other methods of the class
...
}


/**
* @ORM\Entity()
*/
class Product
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;


// Some properties
...

/**
* @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="products")
*/
private $category;


public function getCategory(): ?Category
{
return $this->category;
}

public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}

// Other methods of the class
...

}

有了它,我可以为 Product 对象分配或删除 Category 对象,这是正常情况:

// set category
$categoryId = 25;
$category = $entityManager->getRepository(Category::class)->find($categoryId);
$product->setCategory($category);
...
// remove category
$product->setCategory(null);

但是,我想做的是,在一个特殊的复杂情况下,我有类别 ID(这里是 25),我想将相应的类别设置为产品,但不从中检索类别对象数据库(因为它在实体上下文中,我不想在其中使用 EntityManager)。

有没有办法实现类似的东西:

$categoryId = 25;
$product->setCategoryById($categoryId);


class Product
{
public function setCategoryById(int $categoryId): self
{
???
}
}

这感觉是可能的,因为毕竟在数据库中,它只是存储在产品表列中的类别 ID...但我不知道如何使用 Doctrine 来实现它。

有什么想法吗?谢谢。

最佳答案

您可以使用 Reference Proxies并做这样的事情:

$categoryId = 25;
$product->setCategory(
$entityManager->getReference(Category::class, $categoryId)
);
$entityManager->persist($product);
$entityManager->flush();

关于php - Doctrine:仅使用 id 来设置相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60337274/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com