CakePHP如何用条件检索HABTM数据?

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了CakePHP如何用条件检索HABTM数据?脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用Cake PHP 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'                 => '',),

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

我补充说

public $uses = array('Restaurant');

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

我只需要选择那些厨房= $id的餐厅.
我试图添加

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

}

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

TLDR:

要根据[ HABTM ]协会的条件检索受限制的数据,您需要使用[ Joins ].

说明:

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

注意:如果您遵循[ CakePHP conventions ](您现在看到的),则不需要所有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;
}

//任何控制器

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

脚本宝典总结

以上是脚本宝典为你收集整理的CakePHP如何用条件检索HABTM数据?全部内容,希望文章能够帮你解决CakePHP如何用条件检索HABTM数据?所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。