Reputation: 1822
I have two entities: Product and Category. A product can be in one category, so there is a OneToMany relation between the two entities:
/**
* @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
...
}
With that, I can assign or remove a Category object to Product objects, which is the normal case:
// set category
$categoryId = 25;
$category = $entityManager->getRepository(Category::class)->find($categoryId);
$product->setCategory($category);
...
// remove category
$product->setCategory(null);
BUT, what I want to do, is that in a special an complicated situation, I have the category id (here 25), and I would like to set the corresponding category to a product, but without retrieving the Category object from the database (because it is in an entity context, where I don't want to use the EntityManager).
Is there a way to achieve something like:
$categoryId = 25;
$product->setCategoryById($categoryId);
class Product
{
public function setCategoryById(int $categoryId): self
{
???
}
}
It feels possible because, after all, in the database, it is just the category id which is stored in a column in the product table... but I can't figure how to do it with Doctrine.
Any idea? Thanks.
Upvotes: 7
Views: 3488
Reputation: 6238
You can use Reference Proxies and do something like this:
$categoryId = 25;
$product->setCategory(
$entityManager->getReference(Category::class, $categoryId)
);
$entityManager->persist($product);
$entityManager->flush();
Upvotes: 16
Reputation: 57
I begin with doctrine so I'm not sure of my answer ^^.
Maybe by creating an attribute that retrieves not the complete object but just the id?
Something like that:
/**
* @ORM\Column(name="category_id", type="integer")
*/
private int $categoryId;
Upvotes: 1