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

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

报告相同问题?

悬赏问题

  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害