Reputation: 298
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.
Upvotes: 1
Views: 525
Reputation: 5483
It does recognize the city property in region
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 through foreach
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.
Upvotes: 2