我有两张桌子,一张包含城市,另一张包含国家/地区。每个城市都通过ManyToOne关系(通过字段country_id)链接到一个国家/地区。
我现在需要做的是,从这个数据库中提取每个国家的列表,并将所有城市链接到该数据库。
无法弄清楚如何使用doctrine构建此查询。
答案 0 :(得分:3)
查看OneToMany双向设置
以下是使用注释的示例:
/**
* @Entity
* @Table( name="country" )
*/
class Country
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
public $id;
/**
* @Column( type="string", length=30, name="name", nullable=false )
*/
public $name;
/**
* @OneToMany( targetEntity="City", mappedBy="Country" )
*/
private $cities;
}
/**
* @Entity
* @Table( name="city" )
*/
class City
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
public $id;
/**
* @ManyToOne( targetEntity="Country" )
* @JoinColumn( name="country", referencedColumnName="id" )
*/
public $country;
/**
* @Column( type="string", length=30, name="name", nullable=false )
*/
public $name;
}
您需要将其设置为允许$country->getCities()
方法正常工作
答案 1 :(得分:2)
将OneToMany关系添加到城市和国家/地区之间的国家/地区,然后:
$country->getCity(); //return all linked cities from city table