【问题标题】:Kohana 3.1 ORM: Trying to build subsequent one-to-many relationshipsKohana 3.1 ORM:尝试建立后续的一对多关系
【发布时间】:2011-07-26 05:48:36
【问题描述】:

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

Countries -> 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();

它确实可以识别 region 中的 city 属性,但它返回一个空行,其中所有 city 值都设置为 NULL。

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

【问题讨论】:

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


    【解决方案1】:

    它确实识别区域内的城市财产

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

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

    【讨论】:

    • 很好的回复,非常感谢!最后,它现在可以正常工作了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-22
    • 1970-01-01
    相关资源
    最近更新 更多