I have 2 Entities: Categories and products. How can I build a relationship between these Entities? Category Entity:
class Category
{
private
Add in your Category yml:
oneToMany:
items:
targetEntity: Namespace\TO\YOUR\Entity\Item
mappedBy: category
Add in your Item yml:
manyToOne:
catregory:
targetEntity: Namespace\TO\YOUR\Entity\Category
inversedBy: items
joinColumn:
name: category_id
referencedColumn: id
Add in your Item Entity:
/**
* @var Catregory
*/
protected $catregory;
public function setCategory(Catregory $catregory) {
$this->catregory = $catregory;
}
public function getCatregory() {
return $this->catregory;
}
Add in your Category Entity:
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
.................
/**
* @var Collection of Item
*/
protected $items;
public function __construct() {
$this->items = new ArrayCollection();
}
public function getItems() {
return $this->items;
}
public function setItems(Collection $items) {
$this->items = $items;
}
public function addItem(Item $item) {
if (!$this->Items->contains($item)) {
$item->setCategory($this);
$this->items->add($item);
}
}
public function removeItem(Item $item) {
if ($this->items->contains($item)) {
$this->items->remove($item);
}
}
public function clearItems() {
$this->items->clear();
}