教义中的关系 [英] Relationships in Doctrine
问题描述
我有 2 个实体:类别和产品.如何在这些实体之间建立关系?类别实体:
I have 2 Entities: Categories and products. How can I build a relationship between these Entities? Category Entity:
class Category
{
private $id;
private $name;
private $parent;
public function getChildren()
{
return $this->children;
}
//setters and getters
}
物品实体:
class Items
{
private $id;
private $name;
private $price;
private $color;
private $size;
private $weight;
//getters and setters
}
类别 yml:
AppBundleEntityCategory:
type: entity
oneToMany:
children:
targetEntity: AppBundleEntityCategory
mappedBy: parent
orderBy:
name: ASC
manyToOne:
parent:
targetEntity: AppBundleEntityCategory
inversedBy: children
joinColumn:
name: parentId
referencedColumn: id
table: category
repositoryClass: AppBundleRepositoryCategoryRepository
id:
id:
column: id
type: integer
id: true
generator:
generator:
strategy: AUTO
fields:
name:
type: string
lenght: 255
项目 yml:
AppBundleEntityItems:
type: entity
table: items
repositoryClass: AppBundleRepositoryItemsRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
name:
type: string
length: 255
price:
type: integer
color:
type: string
length: 255
nullable: true
size:
type: integer
weight:
type: integer
一个产品可以属于多个类别,这怎么办?我认为这是多对多关系,但我无法正确建立关系......................................................................................................................................................................
One product can belong to several categories, how can this be done? I think that is the ManyToMany relationship, but I can't build relations correctly. .....................................................................................................................................................................
推荐答案
在你的 Category yml 中添加:
Add in your Category yml:
oneToMany:
items:
targetEntity: NamespaceTOYOUREntityItem
mappedBy: category
在你的 Item yml 中添加:
Add in your Item yml:
manyToOne:
catregory:
targetEntity: NamespaceTOYOUREntityCategory
inversedBy: items
joinColumn:
name: category_id
referencedColumn: id
添加你的物品实体:
/**
* @var Catregory
*/
protected $catregory;
public function setCategory(Catregory $catregory) {
$this->catregory = $catregory;
}
public function getCatregory() {
return $this->catregory;
}
添加您的类别实体:
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
.................
/**
* @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();
}
这篇关于教义中的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!