CakePHP - 使用多个表中的多选链接添加/编辑项目

时间:2011-04-07 15:17:02

标签: php cakephp cakephp-1.3

问题概述:

我希望能够编辑项目(在这种情况下是餐馆),并允许用户选择使用连接表访问选项/菜肴列表的多个选项(菜系)。

问题详情:

我有3张桌子:

restaurants:          id, name, address, phone...etc
cuisines:             id, name, url_name
cuisine_connections:  id, restaurant_id, cuisine_id

您可以想象,cuisine_connections表是美食和餐厅之间的连接列表。 (如果有人有更好的解决方案,我会全力以赴)。

模型/ restaurant.php:

    var $hasMany = array(
    'CuisineConnection' => array(
        'className' => 'CuisineConnection',
        'foreignKey' => 'restaurant_id',
        'dependent' => false
    )
);

模型/ cuisine.php

    var $hasMany = array(
    'CuisineConnection' => array(
        'className' => 'CuisineConnection',
        'foreignKey' => 'cuisine_id'
    )
);

模型/ cuisine_connection.php

var $belongsTo = array(
    'Cuisine' => array(
        'className' => 'Cuisine',
        'foreignKey' => 'restaurant_id',
        'dependent' => false
    ),
    'Restaurant' => array(
        'className' => 'Restaurant',
        'foreignKey' => 'restaurant_id'
    )
);

到目前为止我已尝试过这个:

控制器/ restaurants_controller.php:

$this->set('cuisines', $this->Restaurant->CuisineConnection->Cuisine->find('list'));

admin_add.ctp:

echo $this->Form->input('cuisine_id', array('multiple'=>'checkbox'));

2 个答案:

答案 0 :(得分:2)

听起来像是在寻找http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM

还要注意蛋糕的惯例是cuisines_restaurants,而不是cuisine_connections

答案 1 :(得分:0)

你可以清楚地看到this tutorial关于在CakePhp中实现多对多关联的问题。除此之外,行代码:

$this->set('cuisines', $this->Restaurant->CuisineConnection->Cuisine->find('list'));

有问题。我认为,根据您的描述,您应该列出所有与相应餐厅选择的美食。代码应替换为:

$this->set('cuisines', $this->Cuisine->find('all'));
相关问题