Reputation: 7269
I have 2 entities — NewsItem
and Category
. It is unidirectional association between this entities: 1 NewsItem
has 1 Category
, 1 Category
has many NewsItem
's.
I am trying to create association mapping like in THIS example. What I've tried? My code:
class NewsItem {
// other fields
/**
* @var int
* @ORM\Column(type="integer")
* @ORM\ManyToOne(targetEntity="News\Entity\Category")
*/
protected $category_id;
// other fiels, getters, setters etc
}
After that, I deleted tables in the database manually and run command orm:schema-tool:update --force
in command line. It says that some queries are executed without errors — it's ok. But when I open table Category
in HeidiSQL there are no FOREIGN KEYS there. That means that tables are not linked.
What I did wrong?
You can watch full code of this News\Entity\NewsItem
entity here: click me. News\Entity\Category
entity is here: click me.
Upvotes: 1
Views: 49
Reputation: 100
You have incorrect mapping information for the Category entity.
Your NewsItem.php file should look like this:
namespace Your\Bundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
/**
* @ORM\Table(name="news_item")
* @ORM\Entity
*/
class NewsItem {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Category
*
* @ORM\ManyToOne(targetEntity="Category", inversedBy="news_items")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
// Rest of code omitted.
}
And your Category.php should look like this:
namespace Your\Bundle\Entity;
/**
* @ORM\Table(name="category")
* @ORM\Entity
*/
class Category {
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="NewsItem", mappedBy="category")
*/
private $news_items;
public function __construct(){
$this->news_items = new ArrayCollection();
}
// Rest of code omitted.
}
Upvotes: 1
Reputation: 175
you should remove * @ORM\Column(type="integer")
as it is conflicting with the many-to-one relation.
Even if it is not the cause of the bug, you should also rename protected $category_id;
to protected $category;
Also, your two entities are under the same namespace so it's not necessary to add the related entity's full path. targetEntity="Category"
is enough.
Upvotes: 1