我正在尝试使用注释在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表定义这种关系。
- 各州有一个或多个县。
- 县有一个或多个市政。
- 市属于一个或多个县。
给你。使用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。所有关系都是双向的