I have two PHP model classes named Category and Item. A Category may have many Items and an Item may belong to many Categories.
I have created a ManyToMany relation to both classes:
class Category
{
/**
* @ORMManyToMany(targetEntity="Item", mappedBy="categories", cascade={"persist"})
*/
private $items;
/**
* Add items
*
* @param AkoStoreBundleEntityItem $items
*/
public function addItems(AkoStoreBundleEntityItem $items)
{
$this->items[] = $items;
}
/**
* Get items
*
* @return DoctrineCommonCollectionsCollection
*/
public function getItems()
{
return $this->items;
}
}
And:
class Item
{
/**
* @ORMManyToMany(targetEntity="Category", inversedBy="items", cascade={"persist"})
* @ORMJoinTable(name="item_category",
* joinColumns={@ORMJoinColumn(name="item_id", referencedColumnName="id")},
* inverseJoinColumns={@ORMJoinColumn(name="category_id", referencedColumnName="id")}
* )
*/
private $categories;
/**
* Add categories
*
* @param AkoStoreBundleEntityCategory $categories
*/
public function addCategories(AkoStoreBundleEntityCategory $categories)
{
$this->categories[] = $categories;
}
/**
* Get categories
*
* @return DoctrineCommonCollectionsCollection
*/
public function getCategories()
{
return $this->categories;
}
}
Now in my controller:
$em = $this->getDoctrine()->getEntityManager();
$item = $em->getRepository('AkoStoreBundle:Item')->find($item_id);
$category = $em->getRepository('AkoStoreBundle:Category')->find($category_id);
$category->addItems($item);
$em->flush();
// Render the same page again.
In this page, I show the list of all items in a select field. The user can select one item, and add it to the category.
The list of items which belong to the category are shown below the form.
When the I submit the form, the selected item is added to the list of Category items, and is shown below, but it is not stored in the database, and if refresh the page, it disappears.
Can anyone please help me with this?
Thanks in advance.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…