dousong5492 2011-04-08 05:47 采纳率: 100%
浏览 25
已采纳

CakePHP - HABTM - 将数据从多个表发送到视图

Scenario:

3 tables:
restaurants
cuisines
features

2 join tables:
cuisines_restaurants
features_restaurants

Question:

What is the best way to get data for a single restaurant from my controller to the view which includes not only the restaurant data, but also the cuisines and features that it has.

I have it working with this:

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

And I'm calling it in the view like this:

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 />";

(and repeat for Features)

But this seems overkill, since in all the Cake tutorials I see, the view method in the controller just has:

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

Then they call it like this:

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

Again - it IS working - I just want to know if there's a better way - the way I'm currently doing it seems sloppy compared to all the other slick things Cake does for me! :)

  • 写回答

1条回答 默认 最新

  • dtk31564 2011-04-08 14:11
    关注

    Your working code uses Model::find('all'), but when you want to retrieve just one Restaurant's data, you want to use Model::find('first'). I think you'll find if you change the first parameter of your call from 'all' to 'first', you'll get the data you want in the format you want.


    Somewhat tangentially, there is quite literally no difference between the data returned by the two following calls:

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

    or

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

    Model::read is essentially a wrapper for Model::find('first'), though it also sets the model's internal state a bit (setting the Model::id and Model::data properties before returning data retrieved with Model::find('first')).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?