首页 > 解决方案 > cake php where条件返回所有值

问题描述

我正在使用 cake php 3。我想使用 where 条件获取数据。但它显示了表中的所有数据,而不使用 where 条件过滤数据。这是我插入 where 条件数据的观点

 <?= $this->Form->create() ?>
    <?php
        echo $this->Form->control('category_id', ['options' => $categories,'empty'=>'Choose']);
    ?>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>

这是我的控制器

if(!empty($this->request->data['category_id'])){
        $categoryId = $this->request->data();
        $searcehProduct = $this->Products->searchProductsByCategory($categoryId);
        dd($searcehProduct);
    }

这是我用于 where 条件的 ProductTables.php 代码。

 public function searchProductsByCategory($id){
    $products = TableRegistry::get('Products');
    $query = $products->find('all', [
        'where' => ['category_id' => $id]
    ]);
    return $query;
}

TIA

标签: cakephp-3.0

解决方案


您的错误只是您替换'conditions''where'

在您的控制器中使用

$categoryId = $this->request->getData('category_id');

在你的桌子上使用

'conditions' => ['category_id' => $id]

它应该可以工作

无论如何,这不是创建自定义查找器的方式。但是您甚至不必创建自定义查找器,只需:

使用动态查找器

事实上你可以做

if($this->request->getData('category_id'))
{
    $categoryId = $this->request->getData('category_id');
    $searcehProduct = $this->Products->findByCategoryId($categoryId);
    dd($searcehProduct);
}

无需更改您的表格,这是一个动态构造的查找器


推荐阅读