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


CakePHP - add/edit an item using multi-selection linking from multiple tables

问题概述:

我希望能够编辑一个项目(在这种情况下是一家餐厅(,并允许用户选择多个选项(烹饪(,这些选项使用连接表来访问选项/烹饪列表。

问题详细信息:

我有3张桌子:

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

正如你所能想象的,cuisine_connectionships表是美食和餐馆之间的联系列表。(如果有人对此有更好的解决方案,我洗耳恭听(。

model/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'
    )
);

model/cuisine_connection.php

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

到目前为止,我已经尝试过了:

controllers/restaurants_controller.php:

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

admin_add.ctp:

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

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

还要注意蛋糕的约定是cuisine_restaurants,而不是cuisine_connections

您可以阅读本教程,了解如何在CakePhp中实现多对多关联。除此之外,线路代码:

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

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

$this->set('cuisines', $this->Cuisine->find('all'));