简体   繁体   中英

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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