2

I have a simple table for recursive categories:

id name parent_id - is a link to id, NULL - for root categories 

I need to create a table with foreign key. My class doesn't create this key. How can I change this class to create table with foreign key using "doctrine:schema:create"? What I have tried:

<?php namespace Test\BackEndBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="category") */ class Category { /** * @ORM\Id * @ORM\Column(type="bigint", length=20) * @ORM\GeneratedValue(strategy="AUTO") * @var int */ protected $id; /** * @ORM\Column(type="string", length="255") * @var string */ protected $name; /** * @ORM\Column(name="parent_id", type="bigint", length=20, nullable="true") * @ORM\OneToMany(targetEntity="Category") * @ORM\JoinColumn(name="id", onDelete="CASCADE", onUpdate="CASCADE") * @var int */ protected $parentId; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set name * * @param string $name */ public function setName($name) { $this->name = $name; } /** * Get name * * @return string */ public function getName() { return $this->name; } } 
1
  • @Sybio, thanks boss. See my changes. Commented Sep 4, 2012 at 11:28

1 Answer 1

7

You reversed OneToMany with ManyToOne !

See here: http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html#one-to-many-self-referencing

In fact, you want that plural subcategories can have one parent cat !

What you need:

/** * @OneToMany(targetEntity="Category", mappedBy="parent") */ private $children; /** * @ManyToOne(targetEntity="Category", inversedBy="children") * @JoinColumn(name="parent_id", referencedColumnName="id") */ private $parent; // ... public function __construct() { $this->children = new \Doctrine\Common\Collections\ArrayCollection(); } 

You can replace $parent for $parentId (and mappedBy="parent" for mappedBy="parentId"), but this is not a good coding convention ^^

Sign up to request clarification or add additional context in comments.

1 Comment

the link is down.. here is the updated link: doctrine-orm.readthedocs.org/en/latest/reference/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.