是否可以在Doctrine2中的Association中创建外部字段。主要目的是建立一种关联。
例如, 我们有联系和机会。我需要具有此关联类型的联系人和机会之间的关联。
数据示例:
contact_id | opportunity_id | association_type
------------------------------------------------------
<contact_id> | <opportunity_id> | <Executive Sponsor>
<contact_id> | <opportunity_id> | <Business Evaluator>
是否可以在Doctrine2中实现?
这是我的协会(YAML):
Opportunity:
type: entity
table: opportinity
...
...
...
manyToMany:
contacts:
targetEntity: Contact
joinTable:
name: opportinities_contacts
joinColumns:
opportunity_id:
referencedColumnName: id
inverseJoinColumns:
contact_id:
referencedColumnName: id
由于
答案 0 :(得分:1)
本案例中的最佳做法是创建实体关联类。
基本上,将您的多对多关系拆分为一对多对一关系,并在中间使用新类
创建一个新类“ContactOpportunities”(在我的组织中,我们将它们命名为ToMap =&gt;位于类之间的ContactToOpportunityMap。
class ContactOpportunity {
/**
* @var <FQN>\Contact
*
* @ORM\Id
* @ORM\ManyToOne(targetEntity="<FQN>\Contact", inversedBy='opportunities')
* @ORM\JoinColumns({
* @ORM\JoinColumn(name='Contact_ID', referencedColumnName="id")
* })
protected $contact;
/**
* @var <FQN>\Opportunity
*
* @ORM\Id
* @ORM\ManyToOne(targetEntity="<FQN>\Opportunity", inversedBy='contacts')
* @ORM\JoinColumns({
* @ORM\JoinColumn(name='Opportunity_ID', referencedColumnName="id")
* })
protected $opportunity;
/*
* @var string type
*
* @ORM\Column(name="Association_Type", type="string")
protected $type;
}
或者在yml ...
ContactOpportunity
type: entity
table: opportunities_contacts
...
...
...
manyToOne:
targetEntity: Contact
inversedBy: opportunities
joinColumn:
name: contact_id
referencedColumnName: id
manyToOne:
targetEntity: Opportunity
inversedBy: contacts
joinColumn:
name: opportunity_id
referencedColumnName: id
然后转换现有的类以定位这个新类:
Opportunity:
type: entity
table: opportunity
...
...
...
oneToMany:
contacts:
targetEntity: ContactOpportunity
mappedBy: opportunity
Contact:
type: entity
table: contact
...
...
...
oneToMany:
opportunities:
targetEntity: ContactOpportunity
mappedBy: contact