![](/img/trans.png)
[英]How to get all rows from related table using join in Zend Framework
[英]How to return rows from a related table in single query Zend Framework
我有兩個表,Restaurants和RestaurantHours,我需要在一個結果集中返回它們。 對於“餐廳”表中的每個餐廳,“餐廳小時”表中有7條記錄。
我試圖以以下格式返回數據,以在我的Knockout ViewModel中使用。
結果的所需格式(請注意,省略了某些字段)
array(
'name' => 'restaurant name here',
'description' => 'restaurant description here',
'hours' => array(
'1' => array('open' => 1, 'day' => 1, 'open_time' => '8:00', 'close_time' => 10:00),
'2' => array('open' => 1, 'day' => 2, 'open_time' => '8:00', 'close_time' => 10:00),
'3' => array('open' => 1, 'day' => 3, 'open_time' => '8:00', 'close_time' => 10:00),
'4' => array('open' => 1, 'day' => 4, 'open_time' => '8:00', 'close_time' => 10:00),
'5' => array('open' => 1, 'day' => 5, 'open_time' => '8:00', 'close_time' => 10:00),
'6' => array('open' => 1, 'day' => 6, 'open_time' => '8:00', 'close_time' => 10:00),
'7' => array('open' => 1, 'day' => 7, 'open_time' => '8:00', 'close_time' => 10:00),
)
);
到目前為止,我已經能夠使用下面的選擇來獲取所有餐廳,但是我不確定如何以我想要的格式返回餐廳營業時間,因此在客戶端,我將有一系列餐廳對象,每個人在一周的每一天都有自己的餐廳營業時間集合。 我知道如何聯接表,只是不確定如何使用Zend DB獲得結果集。
餐館
$select = $this->restaurantRepository->select();
$select->setIntegrityCheck(false)
->from('restaurants')
->join('food_types', 'restaurants.food_type = food_types.id', array('foodType' => 'name'))
->order('restaurants.name ASC');
$restaurants = $this->restaurantRepository->getAdapter()->fetchAll($select);
return Zend_Json::encode($restaurants);
餐廳營業時間
// fetch all of the restaurant hours for the specified restaurant
$select = $this->restaurantHoursRepository
->select()
->from('restaurant_hours', array('id', 'restaurant_id', 'open', 'day', 'open_time' => 'DATE_FORMAT(open_time, "%H:%i")', 'close_time' => 'DATE_FORMAT(close_time, "%H:%i")'))
->where('restaurant_id = ' . $restaurant_id);
return Zend_Json::encode($this->restaurantHoursRepository->fetchAll($select));
基本上,我需要將這兩個查詢結合在一起。 現在,我必須返回所有餐廳,然后在ViewModel中綁定餐廳對象時,我要獲取餐廳時間,這意味着很多ajax調用。 我真的很想把這個問題回落到一個電話上,這將加載所有餐廳。
感謝您的所有幫助!
你能試一下嗎
$select = $this->restaurantRepository->select();
$select->setIntegrityCheck(false)
->from('restaurants')
->join('food_types', 'restaurants.food_type = food_types.id', array('foodType' => 'name'))
->join('restaurant_hours', 'restaurants.id = restaurant_hours.restaurant_id', array('id', 'restaurant_id', 'open', 'day', 'open_time' => 'DATE_FORMAT(open_time, "%H:%i")', 'close_time' => 'DATE_FORMAT(close_time, "%H:%i")'))
->order('restaurants.name ASC');
$restaurantsAndHours = $this->restaurantRepository->getAdapter()->fetchAll($select);
return Zend_Json::encode($restaurantsAndHours);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.