情境:
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教程中,控制器中的view方法只有:
$this->set('restaurant', $this->Restaurant->read(null, $id));
然后他们这样称呼:
echo $restaurant['Restaurant']['name'];
...etc
再次 - 它正在运作 - 我只是想知道是否有更好的方式 - 我现在这样做的方式似乎比Cake为我做的所有其他光滑的事情都要邋! :)
答案 0 :(得分:1)
您的工作代码使用Model::find('all')
,但如果您只想检索一个Restaurant的数据,则需要使用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::id
和Model::data
属性{1}})。