嗨,我在项目(产品)和类别之间有多对多的关系,我使用这三个实体实现:
物品实体:
/** * @Entity * @Table(name="items") */ use Doctrine\Common\Collections\ArrayCollection; class Item { /** * * @Id @Column(type="integer") * @GeneratedValue */ private $id_item; /** @OneToMany(targetEntity="ItemCategories", mappedBy="item") */ protected $categories; public function __construct() { $this->categories=new ArrayCollection(); } public function addCategory(ItemCategories $category){ $this->categories->add($category); } public function getCategories(){ return $this->categories; } }
2 连接表(ItemCategories)
/** * @Entity * @Table(name="item_categories") */ class ItemCategories { /** * * @Id @Column(type="integer") * @GeneratedValue */ private $id; /** * @Column(type="integer") */ private $id_item; /** * @Column(type="integer") */ private $id_category; /** @ManyToOne(targetEntity="Category", inversedBy="ItemCategories") * @JoinColumn(name="id_category", referencedColumnName="id_category") * */ protected $category; /** @ManyToOne(targetEntity="Item", inversedBy="$categories") * @JoinColumn(name="id_item", referencedColumnName="id_item") * */ protected $item; public function getCategory() { return $this->category; } public function setCategory($category) { $this->category = $category; } public function getItem() { return $this->item; } public function setItem($item) { $this->item = $item; } }
3.类别表
/** * @Entity * @Table(name="categories") */ class Category { /** * * @Id @Column(type="integer") * @GeneratedValue */ private $id_category; /** @OneToMany(targetEntity="ItemCategories", mappedBy="category") */ protected $ItemCategories; /** * * @Column(type="string") @var string */ }
现在我的问题是我不知道如何使用现有类别插入项目。我试过了:
$item= new Entity\Item();
$itemCategoriesReferences=new Entity\ItemCategories();
$productCategoriesReferences->setItem($product);
//get existing category from db using PkId
$itemCategoriesReferences->setCategory($CategoryModel->getCategory(1));
$item->addCategory(itemCategoriesReferences);
我知道这没有多大意义,但我没有其他想法,所以请帮帮我。
谢谢