我使用Cake
PHP 2.2.2
我有3张桌子:餐厅,厨房和厨房_餐厅 – 连接HABTM表.
我有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:
原文链接:https://www.f2er.com/php/131913.html要根据[ 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); }