簡體   English   中英

Symfony2:按國家列出城市

[英]Symfony2: List cities by country

我有兩個表,一個包含城市,一個包含國家。 每個城市都通過與國家的ManyToOne關系(通過字段country_id)鏈接到一個國家。

我現在需要做的是,從此數據庫中繪制每個國家的列表,並鏈接到所有城市。

無法弄清楚如何使用學說建立此查詢。

看看OneToMany雙向設置

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

這是一個使用注釋的示例:

/**
 * @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()方法起作用

在城市與國家之間添加與國家的OneToMany關系,然后:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM