Kohana 3.1 ORM:尝试建立后续的一对多关系

时间:2011-07-26 05:48:37

标签: kohana kohana-3 one-to-many kohana-orm

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

国家/地区 - > Countries_Regions(FK:country_id) - > Countries_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。

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

1 个答案:

答案 0 :(得分:2)

  

它确实识别了地区的城市房产

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

我认为有一种简单的方法。只需将country_id字段添加到City模型并定义Belong_To关系即可。因此,您可以在不加载区域的情况下使用$country->cities$city->country