0

是否可以在 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

谢谢

4

1 回答 1

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;
 }

或者在 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
于 2013-07-02T18:50:27.890 回答