CakePHP如何检索有条件的HABTM数据?

use*_*327 11 php cakephp has-and-belongs-to-many

我使用CakePHP 2.2.2我有3张桌子:餐馆,厨房和厨房餐厅 - HABTM的连接桌.

在餐厅模型我有:

public $hasAndBelongsToMany = array(
    'Kitchen' =>
        array(
            'className'              => 'Kitchen',
            'joinTable'              => 'kitchens_restaurants',
            'foreignKey'             => 'restaurant_id',
            'associationForeignKey'  => 'kitchen_id',
            'unique'                 => true,
            'conditions'             => '',
            'fields'                 => 'kitchen',
            'order'                  => '',
            'limit'                  => '',
            'offset'                 => '',
        ),
Run Code Online (Sandbox Code Playgroud)

问题是我的主页面有单独的控制器,我需要从复杂条件的模型中检索数据.

我补充道

public $uses = array('Restaurant');
Run Code Online (Sandbox Code Playgroud)

到我的主页控制器,这里是我需要你的建议的部分.

我只需要选择那些厨房= $ id的餐馆.我试过补充一下

public function index() {   
$this->set('rests', $this->Restaurant->find('all', array(
'conditions' => array('Restaurant.active' => "1", 'Kitchen.id' => "1")
)));

}
Run Code Online (Sandbox Code Playgroud)

我得到了SQLSTATE [42S22]:未找到列:1054'where子句'错误中的未知列.显然我需要从"HABTM连接表"中获取数据,但我不知道如何.

Dav*_*ave 24

TLDR:

要检索基于[HABTM]关联条件限制的数据,您需要使用[连接].

说明:

下面的代码遵循[Fat Model/Skinny Controller]的咒语,所以逻辑大部分都在模型中,只是从控制器调用.

注意:如果您遵循[CakePHP约定](您看来是这样),则不需要所有这些HABTM参数.

下面的代码还没有经过测试(我在这个网站上写过),但它应该非常接近,至少可以让你朝着正确的方向前进.

码:

//餐厅模特

public $hasAndBelongsToMany = array('Kitchen');

/**
 * Returns an array of restaurants based on a kitchen id
 * @param string $kitchenId - the id of a kitchen
 * @return array of restaurants
 */
public function getRestaurantsByKitchenId($kitchenId = null) {
    if(empty($kitchenId)) return false;
    $restaurants = $this->find('all', array(
        'joins' => array(
             array('table' => 'kitchens_restaurants',
                'alias' => 'KitchensRestaurant',
                'type' => 'INNER',
                'conditions' => array(
                    'KitchensRestaurant.kitchen_id' => $kitchenId,
                    'KitchensRestaurant.restaurant_id = Restaurant.id'
                )
            )
        ),
        'group' => 'Restaurant.id'
    ));
    return $restaurants;
}
Run Code Online (Sandbox Code Playgroud)

//任何控制器

public function whateverAction($kitchenId) {
    $this->loadModel('Restaurant'); //don't need this line if in RestaurantsController
    $restaurants = $this->Restaurant->getRestaurantsByKitchenId($kitchenId);
    $this->set('restaurants', $restaurants);
}
Run Code Online (Sandbox Code Playgroud)