1:
I know I could have used foreign keys for One to One and One to Many relationships but my personal preference is to make it so the normal tables have no information at all about any other tables (including foreign keys). So, they only contain the information relevant to themselves. I also found doing it this way made the implementation of DataMapper much easier.
DataMapper ensures the integrity of relationships stored in joining tables are kept intact for each of the different relationship types, so you don’t need to worry about your One to One relationship becoming something else, it wont.
2:
Ok, so the Restaurant has a One to One relationship with Menu, and Menu has a One to Many relationship with MenuItem.
There’s several ways you can find which restaurants have the “chicken” dish.
NOTE: I’m assuming the “menuitems” table has a “dish” field, and the “restaurants” table has a “name” field.
Here’s one way (starting with the MenuItem):
// Dish to find
$dish = "chicken";
// Get the menu item the user wants
$menuitem = new MenuItem();
$menuitem->where('dish', $dish)->get();
// Loop through the menu's this dish is on
foreach ($menuitem->menu->all as $menu)
{
// Show the restaurants that the menu belongs to (that has the dish)
echo 'Restaurant ' . $menu->restaurant->name . ' has ' . $dish . '<br />';
}
Here’s another way (starting with all restaurants, to find the restaurants with the dish):
// Dish to find
$dish = "chicken";
// Get all restaurants
$restaurant = new Restaurant();
$restaurant->get();
// Loop through all restaurants
foreach ($restaurant->all as $r)
{
// Loop through all menu items in the restaurants menu
foreach ($r->menu->menuitem->all as $mi)
{
// If the meni item's dish is the same dish we're looking for
if ($mi->dish == $dish)
{
// Show the restaurant that has it
echo 'Restaurant ' . $r->name . ' has ' . $dish . '<br />';
}
}
}
All MenuItems served at “Joe’s Diner”:
// Name of Restaurant
$name = "Joe's Diner";
$r = new Restaurant();
$r->where('name', $name)->get();
echo 'Restaurant ' . $r->name . ' has the following menu items:<br />';
foreach ($r->menu->menuitems->all as $mi)
{
echo $r->dish . '<br />';
}