2011-04-08 56 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