2013-07-01 64 views
0

是否可以在關聯中在Doctrine2中創建外部字段。主要目的是建立一種關聯。例如, 我們有聯繫人和機會。我需要聯繫人和商機之間的關聯與此關聯的類型。數據Doctrine2 - 關聯類型的多對多關聯

例子:

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

[Doctrine2:在參考表中處理多對多列的最佳方法]的可能重複(http://stackoverflow.com/questions/3542243/doctrine2-best-way-to-handle -man-to-many-with-extra-columns-in-reference-table) – Crozin

回答

1

在這種情況下,最好的做法是創建一個實體協會類。

基本上,分裂你很多一對多的關係轉化爲一對多,一對一與一類新的插圖中

創建一個新類「ContactOpportunities」(在我的組織,我們爲它們命名ToMap => 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; 
} 

還是在陽明...

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 
+0

謝謝你。這對我來說非常有用。 – user2539253

+0

如果有用,請選擇Upvote或選擇答案:-) – Fodagus