我有一个属于ToMany标签和类别的产品表。标签和类别也属于ToMany产品。
我正在尝试实施搜索功能,其中包含搜索参数与标记产品,分类产品以及任何产品标题或说明相匹配的任何产品。
这就是我在控制器中所拥有的:
public function index()
{
$this->paginate = [
'sortWhitelist' => [
'Products.title',
'Products.msrp',
'Products.sale_price',
],
'limit' => 48,
'order' => ['Products.title' => 'asc']
];
$products = $this->Products->find();
if ($search = $this->request->query('search')) {
$matchingCategories = $this->Products->find()->matching('Categories', function ($q) use ($search) {
return $q->where(['Categories.name LIKE' => "%$search%"]);
});
$matchingTags = $this->Products->find()->matching('Tags', function ($q) use ($search) {
return $q->where(['Tags.name LIKE' => "%$search%"]);
});
$products
->where(['Products.title LIKE' => "%$search%"])
->orWhere(['Products.description LIKE' => "%$search%"])
->orWhere(['Products.id IN' => $matchingCategories])
->orWhere(['Products.id IN' => $matchingTags]);
}
$this->set('products', $this->paginate($products));
$this->set('_serialize', ['products']);
}
你可以看到我在这里要完成的任务,但它显然不起作用。我可以使等式的任何一部分起作用,这意味着我可以获得具有匹配类别的产品,或具有匹配标签的产品,或者在其标题或描述中具有匹配的产品,但是我无法获得所有产品搜索适合任何这些部分。
答案 0 :(得分:0)
看起来我只需要在子查询中选择id字段,如下所示:
$matchingCategories = $this->Products->find()->select(['Products.id'])->matching('Categories', function ($q) use ($search) {
return $q->where(['Categories.name LIKE' => "%$search%"]);
});
注意:我愿意接受改进建议。