Symfony 2.0模型关系

时间:2011-11-09 23:16:01

标签: php doctrine-orm symfony

我正在尝试使用注释在Symfony 2.0中建模以下表结构。

   State
PK Code
   Name

   County
PK State_Code -> FK State.Code
PK Code
   Name

   Muni
PK State_Code -> FK.State.Code
PK County_Code -> FK County.Code
PK Code
   Name

建模字段和州 - 县关系很简单,但我无法确定如何定义Muni表的关系。

  • 国家有一个或多个县。
  • 县有一个或多个Munis。
  • Munis属于一个或多个县。

表结构是遗留的,无法修改。

1 个答案:

答案 0 :(得分:2)

你走了。使用Symfony 2.0.5(Doctrine 2.1)进行测试:

<强> State.php

namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * State
 *
 * @ORM\Entity
 */
class State
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\OneToMany(targetEntity="County", mappedBy="state_code")
     */
    private $counties;

    /**
     * @ORM\OneToMany(targetEntity="Muni", mappedBy="state_code")
     */
    private $munis;
}

<强> County.php

namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * County
 *
 * @ORM\Entity()
 */
class County
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="State", inversedBy="counties")
     * @ORM\JoinColumn(name="State_Code", referencedColumnName="Code")
     */
    private $state_code;

    /**
     * @ORM\OneToMany(targetEntity="Muni", mappedBy="county_code")
     */
    private $munis;
}

<强> Muni.php

namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Muni
 *
 * @ORM\Entity
 */
class Muni
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="County", inversedBy="munis")
     * @ORM\JoinColumn(name="County_Code", referencedColumnName="Code")
     */
    private $county_code;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="State", inversedBy="munis")
     * @ORM\JoinColumn(name="State_Code", referencedColumnName="Code")
     */
    private $state_code;
}

不要忘记生成getter / setter。所有关系都是双向的。