CakePHP如何用条件检索HABTM数据?
发布时间:2020-12-13 16:39:22 所属栏目:PHP教程 来源:网络整理
导读:我使用Cake PHP 2.2.2 我有3张桌子:餐厅,厨房和厨房_餐厅 – 连接HABTM表. 在餐厅里,我有: public $hasAndBelongsToMany = array( 'Kitchen' = array( 'className' = 'Kitchen','joinTable' = 'kitchens_restaurants','foreignKey' = 'restaurant_id','ass
我使用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子句’错误中的未知列.
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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |