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')).

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

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接