2011-04-08 27 views
1

場景:CakePHP的 - HABTM - 將來自多個表的數據視圖

3 tables: 
restaurants 
cuisines 
features 

2 join tables: 
cuisines_restaurants 
features_restaurants 

問:

什麼是讓數據從我的控制器到一個餐廳的最佳方式不僅包括餐廳數據,還包括它的美食和特色。

我有這個工作:

$restaurant = $this->Restaurant->find('all', array('conditions' => array('Restaurant.id' => $id))); 
$this->set('restaurant', $restaurant); 

而且我稱它在這樣的觀點:

echo "<span class='label'>Name:</span> " . $restaurant[0]['Restaurant']['name'] . "<br />"; 
echo "<span class='label'>Cuisine:</span> "; 
    $cuisineList = ""; 
    foreach($restaurant[0]['Cuisine'] as $cuisine) { 
     $cuisineList .= $cuisine['name'] . ", "; 
    } 
    echo substr($cuisineList,0,-2) . "<br />"; 

(重複的功能)

但這似乎矯枉過正,因爲在我看到的所有Cake教程中,控制器中的視圖方法只有:

$this->set('restaurant', $this->Restaurant->read(null, $id)); 

然後他們這樣稱呼它:

echo $restaurant['Restaurant']['name']; 
...etc 

再次 - 這是工作 - 我只是想知道是否有一個更好的辦法 - 目前我做比較,似乎草率的方式,所有的蛋糕爲我做的其他華而不實的事情! :)

+0

您是否在模型中設置了遞歸?如果將遞歸設置爲2,那麼應該返回一個巨大的數據集。看看Containable,因爲這可以幫助您查看數據集。在我頭頂,你在做什麼應該返回所有的數據。 – 2011-04-08 10:00:12

回答

1

您的工作代碼使用Model::find('all'),但是當您只想檢索一個餐廳的數據時,您想使用Model::find('first')。我想你會發現,如果你將呼叫的第一個參數從'all'更改爲'first',則會以所需的格式獲取所需的數據。


有點相切,也毫不誇張地通過下面的兩個調用返回的數據沒有差別:

$data = $this->Restaurant->find('first', array(
    'conditions'=>array('Restaurant.id'=>$id) 
)); 

$data = $this->Restaurant->read(null,$id); 

Model::read本質上是Model::find('first')的包裝,雖然它還將模型的內部狀態設置了一點(在返回數據之前設置Model::idModel::data屬性用Model::find('first')檢索)。

+1

只需注意 - 我必須設置$ this-> Restaurant-> recursive = 1; (但是你完全正確 - $ this-> Restaurant-> read工作得很好,我發誓我已經試過了,但是 - 我想聽到它的信心應該是正確的,這就迫使你更詳細地檢查你的代碼- 謝謝! – Dave 2011-04-08 17:34:52