1

我有一个如下所示的 MySQL 表结构:

国家 -> Country_Regions (FK: country_id) -> Country_Regions_Cities (FK: region_id)

所以,国家和地区之间是一对多的关系,地区和城市之间是一对多的关系

我试图将它们与以下类链接:

class Model_Country extends ORM {
    protected $_has_many = array('regions' => array("model" => "Countries_Region"));
}

class Model_Countries_Region extends ORM {
    protected $_has_many = array('cities' => array("model" => "Countries_Regions_City"));
    protected $_belongs_to = array('country' => array("model" => "Country"));
}

class Model_Countries_Regions_City extends ORM {
    protected $_belongs_to = array('region' => array("model" => "Countries_Region"));
}

如果我尝试找到所有区域,一切都会好起来的

$country = ORM::factory("country", 1);
$region = $country->regions->find_all();

但是当我试图自下而上找到所有城市时,

$country = ORM::factory("country", 1);
$city = $country->regions->cities->find_all();

它确实识别区域中的城市属性,但它返回一个空行,其中所有城市值都设置为 NULL。

我觉得我错过了一些非常明显的东西,但我无法弄清楚它是什么。请帮我。

4

1 回答 1

2

它确实承认该地区的城市财产

因为$country->regions返回带有准备好的WHERE语句的 ORM 对象,而不是区域列表。如果您调用$country->regions->find_all(),您将获得一系列区域,但之后您只能通过foreach循环访问他们的城市。

我认为有一个简单的方法。只需country_id向 City 模型添加一个字段并定义 Belong_To 关系。因此,您将能够使用$country->cities$city->country不使用加载区域。

于 2011-07-26T07:04:58.060 回答