Symfony2: List cities by country

2019-08-07 01:50发布

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.

2条回答
【Aperson】
2楼-- · 2019-08-07 02:45

Add OneToMany relation to country between city and country, then:

$country->getCity(); //return all linked cities from city table
查看更多
虎瘦雄心在
3楼-- · 2019-08-07 02:47

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

查看更多
登录 后发表回答