简体   繁体   English

Symfony2:按国家列出城市

[英]Symfony2: List cities by country

I have two tables, one containing cities and one containing countries. 我有两个表,一个包含城市,一个包含国家。 Every city is linked to a country by a ManyToOne relation (via field country_id) to a country. 每个城市都通过与国家的ManyToOne关系(通过字段country_id)链接到一个国家。

What I need to do now is, to render a list of every country form this database with all cities linked to it. 我现在需要做的是,从此数据库中绘制每个国家的列表,并链接到所有城市。

Can't figure out, how to build this query using doctrine. 无法弄清楚如何使用学说建立此查询。

Have a look at the OneToMany bi-directional setup 看看OneToMany双向设置

http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/association-mapping.html#one-to-many-bidirectional http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/association-mapping.html#one-to-many-bidirectional

Here is an example using annotations : 这是一个使用注释的示例:

/**
 * @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;
}

You need to set this up to allow the $country->getCities() method to work 您需要对此进行设置,以允许$country->getCities()方法起作用

在城市与国家之间添加与国家的OneToMany关系,然后:

$country->getCity(); //return all linked cities from city table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM