Kohana 3.1 ORM:尝试建立后续的一对多关系
我有一个 MySQL 表结构,如下所示:
Countries ->国家/地区_地区(FK:国家/地区_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。
我觉得我错过了一些非常明显的东西,但我不知道它是什么。请帮我。
I have a MySQL table structure that looks like this:
Countries -> Countries_Regions (FK: country_id) -> Countries_Regions_Cities (FK: region_id)
So, there's a one-to-many relationship between country and region, and there's a one-to-many relationship between region and city
I tried to link them with the following classes:
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"));
}
Everything goes fine if I try to find all the regions with
$country = ORM::factory("country", 1);
$region = $country->regions->find_all();
But when I try to find all the cities bottom-up, with
$country = ORM::factory("country", 1);
$city = $country->regions->cities->find_all();
It does recognize the city property in region, but it returns an empty row with all the city values set to NULL.
I feel like I'm missing something very obvious, but I can't figure out what it is. Please help me.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
,因为
$country->regions
返回带有准备好的 WHERE 语句的 ORM 对象,而不是区域列表。如果你调用$country->regions->find_all()
,你会得到一个地区数组,但之后你只能通过foreach
访问他们的城市环形。我认为有一个简单的方法。只需将
country_id
字段添加到 City 模型并定义 Belong_To 关系即可。因此,您将能够使用$country->cities
或$city->country
而无需加载区域。Because
$country->regions
returns an ORM object with prepared WHERE statements, not a list of regions. If you call$country->regions->find_all()
, you will get an array of regions, but after that you can access to their cities only throughforeach
loop.There is a simple way, I think. Just add a
country_id
field to a City model and define a Belong_To relationship. So you will be able to use$country->cities
or$city->country
without loading regions.