原则:仅使用 id 来设置相关实体

sca*_*del 5 php doctrine symfony

我有两个实体:产品和类别。一个产品可以属于一个类别,因此两个实体之间存在 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 
    ...

}
Run Code Online (Sandbox Code Playgroud)

这样,我可以将 Category 对象分配或删除到 Product 对象,这是正常情况:

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

Run Code Online (Sandbox Code Playgroud)

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

有没有办法实现类似的目标:

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


class Product
{
    public function setCategoryById(int $categoryId): self
    {
        ???
    }
}
Run Code Online (Sandbox Code Playgroud)

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

任何想法?谢谢。

Mic*_*rin 14

您可以使用参考代理并执行以下操作:

$categoryId = 25;
$product->setCategory(
    $entityManager->getReference(Category::class, $categoryId)
);
$entityManager->persist($product);
$entityManager->flush();
Run Code Online (Sandbox Code Playgroud)