两天前我写信询问 andConditions 似乎我不明白这个想法,但事实是两天来我一直坚持使用 CakeDC 的下一步:
如何在 CakeDC 搜索插件的“查询”方法中实现复杂的 HABTM 条件?
我有提供 HABTM 功能(表:提供、功能、功能提供),以下在控制器中使用时效果很好:
debug($this->Offer->find('all', array('contain' => array(
'Feature' => array(
'conditions' => array(
'Feature.id in (8, 10)',
)
)
)
)
)
);
当我想在搜索中使用相同的条件时,问题就来了:
public $filterArgs = array(
array('name' => 'feature_id', 'type' => 'query', 'method' => 'findByFeatures'),
);
........
public function findByFeatures($data = array()) {
$conditions = '';
$featureID = $data['feature_id'];
if (isset($data['feature_id'])) {
$conditions = array('contain' => array(
'Feature' => array(
'conditions' => array(
'Feature.id' => $data['feature_id'],
)
)
)
);
}
return $conditions;
}
我收到一个错误:
错误:SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列 'contain'
这让我认为我根本无法执行此搜索和/或在搜索中使用可包含的行为。
如果我遗漏了什么,或者在该领域有更多经验的人可以告诉我,或者指出我在哪里可以找到解决方案——也许是食谱中的一个部分?
编辑:还尝试了连接。这在控制器中工作得非常好,返回我需要的所有数据:
$options['joins'] = array(
array('table' => 'features_offers',
'alias' => 'FeaturesOffers',
'type' => 'inner',
'conditions' => array(
'Offer.id = FeaturesOffers.offer_id'
),
array('table' => 'features',
'alias' => 'F',
'type' => 'inner',
'conditions' => array(
'F.id = FeaturesOffers.feature_id'
),
)
),
);
$options['conditions'] = array(
'feature_id in (13)' //. $data['feature_id']
);
debug($this->Offer->find('all', $options));
...当我尝试输入搜索方法时,我只在 SQL 的 where 子句中得到返回的条件
WHERE ((joins = (Array)) AND (conditions = ('feature_id in Array')))
...导致错误:
SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列 'joins'
编辑:也许我很愚蠢,很抱歉这么说,但插件的文档很糟糕。
我检查了两次、三次和四次(顺便说一句,至少在搜索表单facepalm的 1 个字段上已经损失了 30 个小时)并且文档中愚蠢的 findByTags 对我来说仍然没有任何意义。
public function findByTags($data = array()) {
$this->Tagged->Behaviors->attach('Containable', array('autoFields' => false));
$this->Tagged->Behaviors->attach('Search.Searchable');
$query = $this->Tagged->getQuery('all', array(
'conditions' => array('Tag.name' => $data['tags']),
'fields' => array('foreign_key'),
'contain' => array('Tag')
));
return $query;
}
据我了解
$this->Tagged
应该是HABTM协会的模型名称。
这与 cakePHP 的标准相去甚远:http: //book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
此处描述的方式表示您不需要其他模型,而是将配方与成分相关联,如下所示:
class Recipe extends AppModel {
public $hasAndBelongsToMany = array(
'Ingredient' =>
array(
'className' => 'Ingredient',
'joinTable' => 'ingredients_recipes',
'foreignKey' => 'recipe_id',
'associationForeignKey' => 'ingredient_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
}
这意味着您可以从配方访问 HABTM 关联表数据,而无需定义模型“IngredientRecipe”。
根据 cakeDC 文档,您需要的模型是 IngredientRecipe,并且在 cakePHP 文档中并未将其指示为强制性内容。即使创建了这个模型,HABTM assoc 也不能正常工作——我也试过了。
现在我需要以我的方式重新编写搜索功能,只使用 cakePHP,尽管我已经花了 30 个小时在它上面……太不高兴了。:(